简体   繁体   English

如何在Python中读取正在进行的进程的stdout输出?

[英]How to read stdout output of ongoing process in Python?

Hello I'm really new to the Python programming language and i have encountered a problem writing one script. 您好我是Python编程语言的新手,我在编写一个脚本时遇到了问题。 I want to save the output from stdout that i obtain when i run a tcpdump command in a variable in a Python script, but i want the tpcdump command to run continuously because i want to gather the length from all packets transferred that get filtered by tcpdump(with the filter i wrote). 我想保存stdout的输出,这是我在Python脚本中的变量中运行tcpdump命令时获得的,但是我希望tpcdump命令能够连续运行,因为我想收集所有被tcpdump过滤的数据包的长度(用我写的过滤器)。 I tried : 我试过了 :

    fin, fout = os.popen4(comand)
    result = fout.read()
    return result

But it just hangs. 但它只是挂起。

I'm guessing that it hangs because os.popen4 doesn't return until the child process exits. 我猜它会挂起,因为os.popen4在子进程退出之前不会返回。 You should be using subprocess.Popen instead. 您应该使用subprocess.Popen

import subprocess
import shlex  #just so you don't need break "comand" into a list yourself ;)

p=subprocess.Popen(shlex.split(comand),stdout=subprocess.PIPE)
first_line_of_output=p.stdout.readline()
second_line_of_output=p.stdout.readline()
...

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

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