无法捕获Java中的命令行输出

时间:2017-10-20 14:21:14

标签: java python cmd

我有一个python脚本,可以在youtube上搜索给定的搜索词,并在控制台上打印出结果。当我在cmd.exe上运行此脚本时,它需要2秒才能打印出结果,但确实如此。但是,我无法捕获Java代码上的命令行输出。它返回一个空的ArrayList。我百分百肯定我在代码中执行与cmd.exe相同的命令。我该怎么做才能在我的Java代码中获得此脚本的输出?提前谢谢。

Java代码:

package musicplayer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Wrapper {

    public static ArrayList<String> search(String searchTerm) throws IOException {

        String projectDirectory = System.getProperty("user.dir");

        ArrayList<String> result = new ArrayList<>();
        String[] commands = {"python",  "'" + projectDirectory + "\\src\\python\\search.py'", "--q","\'"+ searchTerm +"\'"};

        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(commands);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

        String line = "";
        while ((line = stdInput.readLine()) != null)
            result.add(line);

        return result;
    }

    public static void main(String[] args) {
        try {
            System.out.println(search("foo"));
        } catch (IOException exc) {
            exc.printStackTrace();
        }
    }
}

Python脚本:

#!/usr/bin/python
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from oauth2client.tools import argparser

# valid developer key 
DEVELOPER_KEY = "AIzaSyDvIqgHz4EQBm3qPRdonottrythisoneQ0W0Wooh5gYPQ8"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

def youtube_search(options):
  youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    developerKey=DEVELOPER_KEY)

  search_response = youtube.search().list(
    q=options.q,
    part="id,snippet",
    maxResults=options.max_results
  ).execute()

  videos = []
  channels = []
  playlists = []

  for search_result in search_response.get("items", []):
    if search_result["id"]["kind"] == "youtube#video":
      videos.append("%s (%s)" % (search_result["snippet"]["title"],
                                 search_result["id"]["videoId"]))
    elif search_result["id"]["kind"] == "youtube#channel":
      channels.append("%s (%s)" % (search_result["snippet"]["title"],
                                   search_result["id"]["channelId"]))
    elif search_result["id"]["kind"] == "youtube#playlist":
      playlists.append("%s (%s)" % (search_result["snippet"]["title"],
                                    search_result["id"]["playlistId"]))

  print("Videos:\n", "\n".join(videos), "\n")
  print("Channels:\n", "\n".join(channels), "\n")
  print("Playlists:\n", "\n".join(playlists), "\n")


if __name__ == "__main__":

  searchString = '' 

  argparser.add_argument("--q", help=searchString, default=searchString)
  argparser.add_argument("--max-results", help="Max results", default=25)
  args = argparser.parse_args()

  try:
    youtube_search(args)
  except HttpError as e:
    print ("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))

0 个答案:

没有答案