Popen没有实时响应

2024-05-20 00:05:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我花了几个小时寻找一个好方法,用适当的参数执行.exe文件,并检索python代码中显示的控制台日志。我有一个代码sample.exe,它获取两个参数并将它们打印20次,我还有一个主代码运行此脚本并打印控制台日志。这是我的主要剧本

import sys
from threading import Thread
import time
import subprocess
import os
from subprocess import Popen, PIPE

class CommandExecution(Thread):
    def __init__(self):
        Thread.__init__(self)
    
    def run(self):
        exe = os.path.normcase(r'C:\\Users\\...\\...\\...\\...\\...\\...\\...\\sample.exe -i testINFile -o testOUTFile')

        proc = subprocess.Popen(exe, stdout=subprocess.PIPE, shell=True, bufsize=1, universal_newlines=True)
        for line in proc.stdout:
            print(line.strip())

thread_1 = CommandExecution()
thread_1.start()

运行此代码后,在sample.exe完全执行之前不会得到任何响应,然后立即得到以下响应

b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''

然后,我用另一个实现替换了run()函数,但它仍然不起作用。这里是它的另一个实现

   def run(self):

        self.command = os.path.normcase(r'C:\\Users\\...\\...\\...\\...\\...\\...\\...\\sample.exe -i testINFile -o testOUTFile')

        if os.name == 'nt':  # windows
            if isinstance(self.command, str):
                self.command = "powershell" + " " + self.command
            else:
                self.command.insert(0, "powershell")
            print(self.command)
            p = Popen(self.command, stdout=PIPE, shell="false")
            while True:
                line = p.stdout.readline()
                print(line.strip())
                if line == "b''" or p.poll() is not None:
                    break
        return

如果你有任何想法,我将非常高兴听到

更新:

在我看来,问题在于代码卡在Popen行,一旦执行完成,它将转到下一行,并打印所有输出。但问题是为什么会这样


Tags: sample代码importselfosstdoutlineexe