[英]Capturing output stream from python 3
我正在尝试从python脚本捕获执行命令的输出流。 一切顺利,直到该命令是python命令为止。
这是我的函数,它们使用stdout和stderr上的不同回调获取流:
capture_output.py
import sys
import logging
import shlex
import asyncio
async def _read_stream(stream, cb):
while True:
line = await stream.readline()
if line:
cb(line.decode())
else:
break
async def _stream_subprocess(cmd, stdout_cb, stderr_cb):
process = await asyncio.create_subprocess_exec(*cmd,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
await asyncio.wait([
_read_stream(process.stdout, stdout_cb),
_read_stream(process.stderr, stderr_cb)
])
return await process.wait()
def execute(cmd, stdout_cb, stderr_cb):
loop = asyncio.get_event_loop()
rc = loop.run_until_complete(
_stream_subprocess(
cmd,
stdout_cb,
stderr_cb,
))
loop.close()
return rc
def run_command(command,
output_function=lambda x: print("STDOUT: %s" % x),
error_handling=lambda x: print("STDERR: %s" % x),
cwd=None):
execute(shlex.split(command), output_function, error_handling, )
if __name__ == "__main__":
"Get the command on 1st position and run it"
command_str = sys.argv[1]
run_command(command_str)
这是外部命令的示例:
anylongrunning_script.sh
#!/bin/bash
for i in {1..5}
do
echo "$i"
sleep 0.5
done
如果我运行python capture_output.py "sh anylongrunning_script.sh"
,我会看到实时流,一切都进行得很好。
但是,如果运行像这样的python命令python capture_output.py "python anylongrunning_script.py"
:
anylongrunning_script.py
import time
for i in range(1, 6):
print(i)
time.sleep(0.5)
输出将在最后一个块中呈现。 您是否知道在这种情况下,shell“ echo”和python“ print”之间有什么区别?
通过使用-u
选项运行命令来禁用输出缓冲。 尝试python capture_output.py "python -u anylongrunning_script.py"
您可以通过为子进程设置PYTHONUNBUFFERED
env变量来确保所有python进程都使用非缓冲模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.