要从我的Python脚本启动程序,我使用以下方法:
def execute(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = process.communicate()[0]
exitCode = process.returncode
if (exitCode == 0):
return output
else:
raise ProcessException(command, exitCode, output)
Run Code Online (Sandbox Code Playgroud)
因此,当我启动一个类似的过程时Process.execute("mvn clean install"),我的程序会一直等到过程结束,然后我才能获得程序的完整输出.如果我正在运行需要一段时间才能完成的过程,这很烦人.
我可以让我的程序逐行写入进程输出,通过在循环结束之前轮询进程输出或其他内容吗?
**[编辑]抱歉,在发布此问题之前我没有很好地搜索.线程实际上是关键.在这里找到一个示例,说明如何执行此操作:** 来自线程的Python Subprocess.Popen
我正在使用subprocess包从 python 脚本调用一些外部控制台命令,我需要将文件处理程序传递给它以分别返回stdout和stderr。代码大致如下:
import subprocess
stdout_file = file(os.path.join(local_path, 'stdout.txt'), 'w+')
stderr_file = file(os.path.join(local_path, 'stderr.txt'), 'w+')
subprocess.call(["somecommand", "someparam"], stdout=stdout_file, stderr=stderr_file)
Run Code Online (Sandbox Code Playgroud)
这工作正常,并且正在创建具有相关输出的 txt 文件。然而,在忽略文件创建的内存中处理这些输出会更好。所以我使用 StringIO 包来处理它:
import subprocess
import StringIO
stdout_file = StringIO.StringIO()
stderr_file = StringIO.StringIO()
subprocess.call(["somecommand", "someparam"], stdout=stdout_file, stderr=stderr_file)
Run Code Online (Sandbox Code Playgroud)
但这不起作用。失败:
File "./test.py", line 17, in <module>
subprocess.call(["somecommand", "someparam"], stdout=stdout_file, stderr=stderr_file)
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 672, in __init__
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
File "/usr/lib/python2.7/subprocess.py", line 1063, …Run Code Online (Sandbox Code Playgroud)