Python Subprocess.Popen来自一个线程

noa*_*ahd 27 python rsync multithreading subprocess

我正在尝试使用子进程模块和线程内的Popen启动'rsync'.在我调用rsync之后,我还需要读取输出.我正在使用通信方法来读取输出.我不使用线程时代码运行正常.看来,当我使用一个线程时,它会挂在通信呼叫上.我注意到的另一件事是,当我设置shell = False时,在线程中运行时,我从通信中得不到任何回报.

Rya*_*ght 39

您没有提供任何代码供我们查看,但这里的示例与您描述的内容类似:

import threading
import subprocess

class MyClass(threading.Thread):
    def __init__(self):
        self.stdout = None
        self.stderr = None
        threading.Thread.__init__(self)

    def run(self):
        p = subprocess.Popen('rsync -av /etc/passwd /tmp'.split(),
                             shell=False,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)

        self.stdout, self.stderr = p.communicate()

myclass = MyClass()
myclass.start()
myclass.join()
print myclass.stdout
Run Code Online (Sandbox Code Playgroud)

  • 只是好奇你为纠正你的问题做了什么?我处于类似的位置,我有一个子进程,我正在一个线程中运行,我想从中捕获输出,因为它正在执行.一旦应用程序完全终止,'communic()'或'stdout.readlines()'调用返回任何输出的唯一时间.如果我从线程中提取相同的代码,它就可以正常工作. (16认同)

小智 13

这是一个不使用线程的优秀实现: 不断打印 - 子进程 - 输出 - 进程正在运行

import subprocess

def execute(command):
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = ''

    # Poll process for new output until finished
    for line in iter(process.stdout.readline, ""):
        print line,
        output += line


    process.wait()
    exitCode = process.returncode

    if (exitCode == 0):
        return output
    else:
        raise Exception(command, exitCode, output)

execute(['ping', 'localhost'])
Run Code Online (Sandbox Code Playgroud)

  • 应该注意的是,这个实现将阻止`process.stdout.readline()`. (6认同)