【发布时间】:2018-03-09 13:50:02
【问题描述】:
Python 3.6
我想从使用subprocess 模块运行的子进程中获取所有输入。我可以轻松地将此输出通过管道传输到日志文件,而且效果很好。
但是,我想过滤掉很多行(来自我无法控制的模块的大量嘈杂输出)。
尝试 1
def run_command(command, log_file):
process = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, bufsize=1,
universal_newlines=True)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output and not_noisy_line(output):
log_file.write(output)
log_file.flush()
return process.poll()
但这在我的子进程和输出之间引入了竞争条件。
尝试 2
我创建了一个新方法和一个类来包装日志记录。
def run_command(command, log_file):
process = subprocess.run(command, stdout=QuiteLogger(log_file), stderr=QuiteLogger(log_file), timeout=120)
return process.returncode
class QuiteLogger(io.TextIOWrapper):
def write(self, data, encoding=sys.getdefaultencoding()):
data = filter(data)
super().write(data)
然而,这只是完全跳过了我的过滤器功能,我的 write 方法根本不被子进程调用。 (如果我打电话给QuietLogger().write('asdasdsa'),它会通过过滤器)
有什么线索吗?
【问题讨论】:
-
“我的子进程和输出之间的竞争条件”是什么意思?这种竞争条件是如何表现出来的?
-
两个进程都进入睡眠状态。
标签: python python-3.x subprocess python-3.6