从Java运行时调用时,Python脚本OSError

时间:2019-03-18 15:36:21

标签: java python-2.7 subprocess

我有一个看起来像这样的python脚本(称为python_prog.py

#!/usr/bin/env python

import tempfile
import subprocess

with tempfile.NamedTemporaryFile() as file:
    # populate file with data
    # then call another program, passing file.name as an arg:
    return subprocess.check_output([command_line_program, file.name, option1, option2])

我可以从命令行按名称呼叫python_prog.py

$>  python_prog.py  option1 option2

这很好。问题来自尝试从Java程序调用{​​{1}}。我在Java代码中使用python_prog.py

Runtime.getRuntime().exec()

当我从Java运行此代码段时,我从 String[] command = new String[] { "python_prog.py", "option1", "option2" }; try { Process process = Runtime.getRuntime().exec(command); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream())); StringBuilder builder = new StringBuilder(); StringBuilder errorBuilder = new StringBuilder(); reader.lines().forEach(builder::append); error.lines().forEach(errorBuilder::append); String outputString = builder.toString(); String errorString = errorBuilder.toString(); catch(IOException e) { // do something } 调用中收到python错误。 subprocess.check_output()字符串的值是:

errorString

我怀疑嵌套壳中的某个地方没有tempfile,但是,我不明白为什么。

这里有什么想法吗?

edit:确切的python子进程调用如下:

Traceback (most recent call last):
  File "python_prog.py", line 9, in __main__
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 566, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

0 个答案:

没有答案