简体   繁体   English

Python子进程永不退出,并在输出中不断提供空字符串

[英]Python subprocess never exits and keeps giving empty strings in output

So, I have been facing a problem with using subprocess for a python app i am writing. 所以,我一直在为我正在编写的python应用程序使用子进程时遇到问题。 To illustrate the problem, I wrote this small script that replicates my problem pretty well. 为了说明问题,我编写了这个小脚本,很好地复制了我的问题。

from __future__ import print_function

import subprocess as sp
from select import select

p = sp.Popen(['ls'], stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)
p.stdin.close()

while p.returncode is None or p.stdout.closed or p.stderr.closed:
    # print('returncode is', p.returncode)
    available_readers = select([p.stdout, p.stderr], [], [], 2.0)[0]
    for r in available_readers:
        print(r.read(1))
        # output_display.insert(tk.END, r.read(1))

Ofcourse, we all know that ls command exists immediately after printing some stuff to stdout (or may be stderr ), but the above script never exists. 当然,我们都知道ls命令在将某些内容打印到stdout (或可能是stderr )后立即存在,但是上面的脚本从不存在。

As you can see from the last line (comment) in the above script, I have to put the content from the subprocess into a tk text component. 从上面脚本的最后一行(注释)可以看到,我必须将子流程中的内容放入tk文本组件中。 So, I can't use methods like .communicate and other blocking calls as the command I need to run takes a long time and I need to show the output (almost) realtime. 因此,我无法使用.communicate方法以及其他阻止调用的方法,因为我需要运行的命令会花费很长时间,并且需要(几乎)实时显示输出。 (Ofcourse, I have to run this in a separate thread when running Tk, but that's something else). (当然,在运行Tk时,我必须在单独的线程中运行它,但这是另外一回事)。

So, I am unable to understand why this script never exits. 因此,我无法理解为什么该脚本永不退出。 It keeps printing empty strings forever (after the expected output of the ls command). 它保持永远打印空字符串(在ls命令的预期输出之后)。

Please advise. 请指教。 I am running python 2.6.6 on ubuntu 10.10 我在ubuntu 10.10上运行python 2.6.6

Edit: Here's the version of the above script that works 编辑:这是上面工作的脚本的版本

from __future__ import print_function

import subprocess as sp
from select import select

p = sp.Popen(['ls'], stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)
p.stdin.close()

while p.poll() is None:
    # print('returncode is', p.returncode)
    available_readers = select([p.stdout, p.stderr], [], [], 2.0)[0]
    for r in available_readers:
        print(r.read(1), end='')
        # output_display.insert(tk.END, r.read(1))

print(p.stdout.read(), end='')
print(p.stderr.read(), end='')
while p.returncode is None or p.stdout.closed or p.stderr.closed:

loops while any of the conditions is true. 任何条件为真时循环执行。 You probably meant to check just returncode (and poll in every iteration). 您可能只检查returncode (并在每次迭代中poll )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM