0

我有一个运行子进程的脚本,如下所示:

child_process = subprocess.Popen(["python", testset['dir'] + testname, \                                                                                                                                     
                              output_spec_file, plugin_directory],\                                                          
                              stderr=subprocess.PIPE, stdout=subprocess.PIPE)

在那个过程中,我试图插入打印语句,但它们没有出现在标准输出中。我尝试sys.stdout.write()在该子进程中使用,然后立即使用sys.stduout.read()child_process但它没有捕获输出。

我是 Python 新手,我还没有达到 Python 的复杂程度。我实际上在 C 语言中工作,并且有一些 Python 测试脚本,我不确定如何从子进程中打印出来。

有什么建议么?

4

1 回答 1

1

sys.stdout.read(and ) 用于当前进程(不是子进程write)的标准输入/输出。如果要写入子进程的标准输入,则需要使用:

child_process.stdin.write("this goes to child")  #Popen(..., stdin=subprocess.PIPE)

与从孩子的标准输出流中读取类似:

child_process = subprocess.Popen( ... , stdout=subprocess.PIPE)
child_process.stdout.read("This is the data that comes back")

当然,通常使用更习惯用法:

stdoutdata, stderrdata = child_process.communicate(stdindata)

(注意subprocess.PIPE在适当的情况下传递给 Popen 构造函数)前提是您的输入数据可以一次全部传递。

于 2012-10-09T03:37:27.683 回答