2016-05-30 100 views
0

我试图从Java执行python脚本。当我手动执行python脚本时,它正常工作。当我从Java执行它时,它的参数有问题:事实上,python会响应“Usage”错误,就好像我没有传递参数一样。从Java执行Python脚本 - 传递参数的问题

Java代码:

  String pythonCommand="python /path/to/myscript.py --key='value list here' -otherparam=param"; 
      p = Runtime.getRuntime().exec(pythonCommand); 

      String line; 
      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); 
      BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream())); 
      p.waitFor(); 
      logger.debug("Exit value: "+p.exitValue()); 
      while ((line = input.readLine()) != null) { 
       logger.debug("Python command output: " +line); 
      } 
      while ((line = error.readLine()) != null) { 
       logger.debug("Python command ERROR output: " +line); 
      } 
      input.close(); 

我再说一遍,脚本工作正常,如果我只是复制粘贴&执行字面上是在我的“pythonCommand”字符串,但如果我从Java执行它,它说:

2016-05-30 09:46:32 [threadName] DEBUG - Executing command: python /path/to/myscript.py --key='value list here' -otherparam=param 
2016-05-30 09:46:32 [threadName] DEBUG - Exit value: 1 
2016-05-30 09:46:32 [threadName] DEBUG - Python command ERROR output: Usage: 
2016-05-30 09:46:32 [threadName] DEBUG - Python command ERROR output: myscript.py [--key=<value list here>] --otherparam=<param> 
2016-05-30 09:46:32 [threadName] DEBUG - Python command ERROR output: myscript.py (-h | --help) 
2016-05-30 09:46:32 [threadName] DEBUG - Python command ERROR output: myscript.py --version 

这里有什么问题?

编辑:另一个重要的信息!如果我执行一个没有参数的Python脚本,比如“python /path/to/test.py”,它可以很好地工作。

EDIT2:我已经尝试执行一个Python脚本,不包含“或”多字的参数,它的工作所以多字的参数问题,肯定是我应该如何通过他们

回答

0

?据我记得你必须将你的命令行分成一个String []像这样:

Runtime.getRuntime().exec(new String[]{"python","/path/to/myscript.py", "--key", "value list here", "-otherparam", "param"}); 
+0

对不起,没有工作。我不得不使用pythonCommand.split(“”),因为我没有构建命令,但它传递给我的函数。 String [] commands = pythonCommand.split(“”); logger.debug(“Exe切割命令:“+命令); p = Runtime.getRuntime()。exec(commands); – user3804769

+0

此外,从我的更复杂的测试中,它看起来像多字参数(包含它们中的空格)是问题。 – user3804769

+0

如果您的值列表包含如示例中所示的空格(“值列表此处”),则简单的split()会混淆您的命令。 logger.debug的输出是什么(“执行命令:”+命令);? – Frank