我正在尝试从Java执行python脚本。当我手动执行python脚本时,它正常工作。当我从Java执行它时,它有参数问题:实际上,python响应“Usage”错误,好像我没有传递参数。
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 :(得分:0)
据我记得,您必须将命令行拆分为String [],如下所示:
Runtime.getRuntime().exec(new String[]{"python","/path/to/myscript.py", "--key", "value list here", "-otherparam", "param"});