我正在尝试在Windows上获取子进程输出,在TimeoutExpired异常被触发的同时。有什么想法吗?
try:
proc = subprocess.run(cmd,timeout=3)
except subprocess.TimeoutExpired:
print(???)
我正在尝试在Windows上获取子进程输出,在TimeoutExpired异常被触发的同时。有什么想法吗?
try:
proc = subprocess.run(cmd,timeout=3)
except subprocess.TimeoutExpired:
print(???)
当超时到期时,您需要使用Popen和subprocess.PIPE来捕获进程输出。特别地,Popen.communicate是您所需的。
这里是一个例子proc = subprocess.Popen(["ping", "192.168.1.1"],
stdout=subprocess.PIPE)
try:
output, error = proc.communicate(timeout=2)
except subprocess.TimeoutExpired:
proc.kill()
output, error = proc.communicate()
print(output)
print(error)
timeout
(其中之一是Python版本过旧),这里是我的解决方案,可以在任何Python版本上运行:
subprocess
对象我正在使用Python子进程,并使用 -u
(无缓冲)选项运行:
transmitter.py:(测试程序每1/10秒打印“hello xx”)
import time
i=0
while True:
print("hello {}".format(i))
i += 1
time.sleep(0.1)
import subprocess,threading,time
def timeout(p,timeout):
time.sleep(timeout)
p.kill()
p = subprocess.Popen(["python","-u","transmitter.py"],stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
t = threading.Thread(target=timeout,args=(p,1.5))
t.start()
output = []
for line in p.stdout:
output.append(line.decode())
t.join()
print("".join(output))
hello 0
hello 1
hello 2
hello 3
hello 4
hello 5
hello 6
hello 7
hello 8
hello 9
hello 10
hello 11
hello 12
hello 13
hello 14
这里是捕获 multiprocessing.Process 的标准输出的方法
import app
import sys
import io
from multiprocessing import Process
def run_app(some_param):
sys.stdout = io.TextIOWrapper(open(sys.stdout.fileno(), 'wb', 0), write_through=True)
app.run()
app_process = Process(target=run_app, args=('some_param',))
app_process.start()
# Use app_process.termninate() for python <= 3.7.
app_process.kill()
TimeoutExpired
异常似乎拥有stdout
和stderr
属性,用于该目的(假设您在调用run
时设置了capture_output=True
)。然而,目前它对我似乎不起作用。 - ingomueller.net