Python Subprocess.Popen 从一个线程

2022-01-18 00:00:00 python rsync subprocess multithreading

问题描述

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

I'm trying to launch an 'rsync' using subprocess module and Popen inside of a thread. After I call the rsync I need to read the output as well. I'm using the communicate method to read the output. The code runs fine when I do not use a thread. It appears that when I use a thread it hangs on the communicate call. Another thing I've noticed is that when I set shell=False I get nothing back from the communicate when running in a thread.


解决方案

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

You didn't supply any code for us to look at, but here's a sample that does something similar to what you describe:

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

相关文章