Skip to main content
 首页 » 编程设计

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

2025年05月04日10Free-Thinker

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

请您参考如下方法: