简体   繁体   English

如何捕获子进程的stdout输出?

[英]How can I capture the stdout output of a child process?

I'm trying to write a program in Python and I'm told to run an .exe file. 我正在尝试用Python编写程序,并且我被告知要运行.exe文件。 When this .exe file is run it spits out a lot of data and I need a certain line printed out to the screen. 当运行此.exe文件时,它会吐出大量数据,我需要在屏幕上打印一行。 I'm pretty sure I need to use subprocess.popen or something similar but I'm new to subprocess and have no clue. 我很确定我需要使用subprocess.popen或类似的东西,但我是subprocess的新手并且没有任何线索。 Anyone have an easy way for me to get this done? 任何人都有一个简单的方法来完成这项工作?

@Paolo's solution is perfect if you are interested in printing output after the process has finished executing. 如果您对过程执行完毕后打印输出感兴趣,@ Paolo的解决方案是完美的。 In case you want to poll output while the process is running you have to do it this way: 如果你想在进程运行时轮询输出,你必须这样做:

process = subprocess.Popen(cmd, stdout=subprocess.PIPE)

while True:
    out = process.stdout.readline(1)
    if out == '' and process.poll() != None:
        break
    if out.startswith('myline'):
        sys.stdout.write(out)
        sys.stdout.flush()

Something like this: 像这样的东西:

import subprocess
process = subprocess.Popen(["yourcommand"], stdout=subprocess.PIPE)
result = process.communicate()[0]

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

相关问题 如何捕获通过管道流程生成的子流程的输出? - How can I capture the output of a child process spawned by a piped process? 多处理:我怎样才能 ʀᴇʟɪᴀʙʟʏ 从子进程重定向标准输出? - multiprocessing: How can I ʀᴇʟɪᴀʙʟʏ redirect stdout from a child process? 如何仅使用 fork/exec/pipe/dup2 捕获子进程的标准输出? - How to capture the stdout of a child process using fork/exec/pipe/dup2 only? Python ASTEVAL。 我如何捕获标准输出 - Python ASTEVAL. How can i capture stdout 如何在 Snowflake 中的 Python UDF 上捕获 STDOUT 以作为字符串返回? - How can I capture STDOUT on a Python UDF in Snowflake to return as string? 如何使用 pytest 捕获日志标准输出 output? - How to capture logbook stdout output with pytest? 如何只为一个进程选择性地将stdout保存在文件中? - How can I selectively save stdout in a file only for one process? 如何在Python中读取正在进行的进程的stdout输出? - How to read stdout output of ongoing process in Python? 如何通过队列传递子进程标准输出? 蟒蛇 - How can I pass a child processes stdout with queue? Python 如何捕获在IIS,FastCGI和WSGI下运行的Python进程的STDOUT? - How to capture STDOUT of a Python process running under IIS, FastCGI, and WSGI?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM