如何同步Python子流程的输出

如何同步Python子流程的输出,python,popen,Python,Popen,我想我在同步同时运行的两个Popen的输出时遇到了问题。这两个不同命令行的输出似乎是相互交错的。我还尝试使用RLock来防止这种情况发生,但没有成功 示例输出为: cmd1 cmd1 cmd2 cmd2 cmd2 cmd2 cmd1 cmd2 代码见附件: import subprocess import threading class PopenWorkerThread(threading.Thread): def __init__(self, cmdLine):

我想我在同步同时运行的两个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

也许你在寻找等待的方法


您锁定的是一行的粒度,因此当然,一个线程的行可以和另一个线程的行交替使用。只要您愿意等到流程结束后再显示其任何输出,就可以使用更大的“流程”粒度进行锁定。当然,您必须对两个线程使用相同的锁——让每个线程使用一个完全独立的锁,就像您现在所做的那样,显然无法实现任何目标

例如:

导入子流程 导入线程

类PopenWorkerThread(threading.Thread):

def启动(): 命令行=['ls-l','netstat'] 对于命令行中的cmdLine: workerThread=PopenWorkerThread(cmdLine) workerThread.start()

发射()

lock = threading.RLock()  # per-class, NOT per-instance!

def __init__(self, cmdLine):
    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)
    result, _ = proc.communicate()
    with self.lock:
        print result,