python - 如何同步Python子进程的输出

标签 python popen

我想我在同步两个同时运行的 Popen 的输出时遇到了问题。这两个不同命令行的输出似乎相互交错。我也尝试使用 RLock 来防止这种情况发生,但它没有用。

示例输出为:

cmd1
cmd1
cmd2
cmd2
cmd2
cmd2
cmd1
cmd2

代码如附件:

import subprocess
import threading

class PopenWorkerThread(threading.Thread):
    def __init__(self, cmdLine):
        self.lock = threading.RLock()
        self.WebSphereCmdLine = cmdLine
        threading.Thread.__init__(self)

    def run(self):
        logger.error('Runninf: ' + self.WebSphereCmdLine)
        proc = subprocess.Popen(self.WebSphereCmdLine, shell=False, stdout=subprocess.PIPE)
        while True:
            self.lock.acquire()
            print proc.stdout.readline()
            self.lock.release()

def launch():
    commandLine = ['ls -l', 'netstat']
    for cmdLine in commandLine:
        workerThread = PopenWorkerThread(cmdLine)
        workerThread.start()

launch()

有没有办法同步输出,使它们看起来像这样?

cmd1
cmd1
cmd1
cmd1
cmd1
cmd2
cmd2
cmd2
cmd2
cmd2

最佳答案

关于python - 如何同步Python子进程的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3205990/

相关文章:

python - 以正确的方式终止一个进程及其子进程以 subprocess.popen 开始(windows 和 linux)

python - 如何捕获从另一个 python 脚本执行的 python 脚本的打印?

python - 将 numpy 数组转换为十六进制字节数组

python - 使用 opencv 为捕获和存储的视频流获得非常高的 fps

python - 在 Python 中使用 PIL 读取 PNG

python 字符串作为十六进制以 null 结尾

python - 实时 subprocess.Popen 通过 stdout 和 PIPE

Go:与另一个进程的双向通信?

c++ - mingw:使用 -std=c++11 编译时找不到函数

python - 为什么 inspect.currentframe 比 sys.currentframe 慢_getframe?