简体   繁体   English

使用 Python 中的 subprocess.check_output 捕获日志记录 output

[英]Capture logging output using subprocess.check_output in Python

I'm running a Telegram bot which is basically an interface to a Bayesian classifier that I made.我正在运行一个 Telegram 机器人,它基本上是我制作的贝叶斯分类器的接口。 I made a command to start a test on the remote server and the tester was originally using the logging module to print information about the test to stdout.我发出命令在远程服务器上开始测试,测试人员最初使用logging模块将有关测试的信息打印到标准输出。 When I tried to spawn a subprocess through subprocess.check_output I noticed that both stdout and stderr where empty byte strings.当我尝试通过subprocess.check_output生成子进程时,我注意到 stdout 和 stderr 都在其中空字节字符串。 I worked around this by replacing the last logging.info call, the one that really matters, with a print function.我通过使用print function 替换最后一个真正重要的logging.info调用来解决这个问题。 What I'm guessing is that logging does not write on the same stdout that subprocess.check_output is expecting?我猜是logging不会写在subprocess.check_output期望的相同标准输出上? Am I doing something wrong?难道我做错了什么?

EDIT编辑

As asked I'm adding a bit more context about what code I'm actually running.如被问及,我正在添加更多关于我实际运行的代码的上下文。 I don't know if this matters, but for the sake of completeness I'll add that the framework I'm using to run the bot is pyrogram.我不知道这是否重要,但为了完整起见,我会补充一点,我用来运行机器人的框架是 pyrogram。

The tester that gets called by the bot can be found here , while the code of the bot calling that script is here机器人调用的测试器可以在这里找到,而机器人调用该脚本的代码在这里

I'm guessing is that logging does not write on the same stdout that subprocess.check_output is expecting?我猜是日志记录不会写在 subprocess.check_output 期望的同一个标准输出上?

logging doesn't write to stdout at all (by default); logging根本不写入标准输出(默认情况下); it writes to stderr.它写入标准错误。

You will need to either redirect your stderr to stdout by adding the stderr argument thus: subprocess.check_output(..., stderr=subprocess.STDOUT) or you will need to use one of the other subprocess functions such as run that gives access to stderr.您将需要通过添加stderr参数将您的 stderr 重定向到 stdout: subprocess.check_output(..., stderr=subprocess.STDOUT)或者您需要使用其他子进程函数之一,例如run标准错误。

The docs do say:文档确实说:

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle调用子流程的推荐方法是对它可以处理的所有用例使用 run() function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM