【问题标题】:Printing to stdout in subprocess在子进程中打印到标准输出
【发布时间】:2012-09-29 08:05:23
【问题描述】:

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

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

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

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

有什么建议吗?

【问题讨论】:

  • 你为什么要在一个新的解释器中运行你的 python 脚本,而不是简单地将它作为一个模块使用?

标签: python subprocess


【解决方案1】:

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

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 构造函数)前提是您的输入数据可以一次全部传递。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 2018-02-25
    • 2013-06-29
    • 1970-01-01
    相关资源
    最近更新 更多