[英]how can the sh python module log stderr/stdout and only capture stdout?
Using the sh module, I would like to log the stdout/stderr of the process and capture stdout for processing. 使用sh模块,我想记录进程的stdout / stderr并捕获stdout进行处理。 The process may take a long time and logging must not wait until the process is finished so the user sees the output in real time. 该过程可能需要很长时间,并且日志记录必须等到该过程完成后才能等待,以便用户实时查看输出。
The following works fine to log stdout/stderr. 以下可以正常记录stdout / stderr。 But stdout is mixed with stderr and there is no convenient way to separate one from the other. 但是stdout与stderr混合在一起,没有方便的方法将它们彼此分开。
import sh
import logging
logger = logging.getLogger(__name__)
command = sh.bash('-c', 'echo a; echo b >&2', _iter=True, _err_to_out=True)
for line in command:
logger.error(line)
print(command.stdout)
the output is like this: 输出是这样的:
a
b
b'a\nb\n'
Is there a way to do the same but without mixing stdout
and stderr
? 有没有办法做到这一点,但又不将stdout
和stderr
混在一起?
The solution is to set _out and _err to the desired logging function ( logging.error for instance). 解决方案是将_out和_err设置为所需的日志记录功能(例如logging.error )。 It will be called as soon as a new line is read from either stderr
or stdout
and the user will be shown the output incrementally. 从stderr
或stdout
读取新行后,它将立即被调用,并且将向用户逐步显示输出。
When _out
or _err
are set, however, sh
does not collect the output and it will not be available for processing. 但是,设置_out
或_err
时, sh
不会收集输出,并且将无法进行处理。 This is what _tee=True is for: it collects stdout
and stderr
even when _out
or _err
are set. 这就是_tee = True的作用:即使设置了_out
或_err
它也会收集stdout
和stderr
。
import sh
import logging
logger = logging.getLogger(__name__)
command = sh.bash('-c', 'echo a; echo b >&2',
_tee=True,
_out=lambda x: logger.error(x.strip()),
_err=lambda x: logger.error(x.strip()))
print(command.stdout)
the output is 输出是
a
b
b'a\n'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.