在执行期间,有许多与Python子流程和stdout读取有关的问题和答案,但我还没有找到满足这些要求的解决方案:
例如,如果正在运行的进程没有生成stdout数据,则进程stdout.read()和stdout.readline()会阻塞,从而阻止进程kill()因超时而终止。
开始代码:
# Python 3.3 syntax
import sys
import subprocess
def subproc(args, stdout):
proc = subprocess.Popen(args, stdout=subprocess.PIPE, shell=False, universal_newlines=True)
while True: # while is broken by return
try:
outs = '' # Clear before communication attempt
outs = proc.communicate(timeout=1)[0] # Timeout every second to process stdout
except subprocess.TimeoutExpired:
pass
# Processing termination using proc.kill is added later
sys.__stdout__.write('Shows that proc communicate timeout works\n')
if outs:
stdout.write(outs) # Allow stdout processing
if proc.returncode is not None: # Completed execution
return proc.returncode # End while and return
class StdHandle:
def write(self, str):
# Additional processing ...
sys.__stdout__.write(str)
def flush(self):
pass
rc = subproc(('proc.sh'), stdout=StdHandle())
print('Return code:', rc)
# EOF