简体   繁体   English

捕获 runpy.run_module 标准输出

[英]Capturing runpy.run_module stdout

I'm unable to capture stdout of runpy.run_module into a variable using StringIO.我无法使用 StringIO 将 runpy.run_module 的标准输出捕获到变量中。
To demonstrate the problem, I created a script called runpy_test.py (code below) using an arg switch;为了演示这个问题,我使用 arg 开关创建了一个名为 runpy_test.py 的脚本(代码如下);

  • 0 = do not redirect stdout. 0 = 不重定向标准输出。
  • 1 = redirect using StringIO, capture into variable, print variable. 1 = 使用 StringIO 重定向,捕获到变量,打印变量。

Console Output控制台 Output

(base) PS C:\Users\justi\Documents> python .\runpy_test.py 0  
pip 20.0.2 from C:\ProgramData\Anaconda3\lib\site-packages\pip (python 3.6)  
(base) PS C:\Users\justi\Documents> python .\runpy_test.py 1  
(base) PS C:\Users\justi\Documents>  

I was expecting python.\runpy_test.py 1 to print pip 20.0.2 from C:\ProgramData\Anaconda3\lib\site-packages\pip (python 3.6) , but as you can see from the above console capture, I'm getting nothing. I was expecting python.\runpy_test.py 1 to print pip 20.0.2 from C:\ProgramData\Anaconda3\lib\site-packages\pip (python 3.6) , but as you can see from the above console capture, I'm一无所获。

runpy_test.py运行py_test.py

import io
import sys
import runpy
import copy

capture_stdout = bool(sys.argv[1] == "1")
if capture_stdout:
    _stdout = sys.stdout
    sys.stdout = io.StringIO()
_argv = copy.deepcopy(sys.argv)
sys.argv = ['', '-V']
runpy.run_module("pip", run_name="__main__")
sys.argv = _argv
if capture_stdout:
    result = sys.stdout.getvalue()
    sys.stdout = _stdout
    print(f"result: {result}")

I'm guessing sys.stdout is not being correctly re-initialised before I print because of something related to runpy.run_module , but not really sure how to debug.我猜sys.stdout在打印之前没有被正确地重新初始化,因为与runpy.run_module相关,但不确定如何调试。 Any ideas would be great, solutions even better.任何想法都会很棒,解决方案会更好。
My environment is Python 3.6.10 using conda 4.8.3.我的环境是 Python 3.6.10 使用 conda 4.8.3。
Thanks in advance.提前致谢。

Using subprocess.check_output instead of runpy.run_module solved my problem.使用subprocess.check_output而不是runpy.run_module解决了我的问题。
See Installing python module within code请参阅在代码中安装 python 模块

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

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