问题描述
我花了几个小时发现了一个很好的方法来执行带有适当参数的 .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 行,一旦执行完成,它将转到下一行,并打印所有输出。但问题是为什么会发生这种情况?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)