相关疑难解决方法(0)

python中subprocess.PIPE上的非阻塞读取

我正在使用子进程模块启动子进程并连接到它的输出流(stdout).我希望能够在其标准输出上执行非阻塞读取.有没有办法让.readline非阻塞或在我调用之前检查流上是否有数据.readline?我希望这是可移植的,或至少在Windows和Linux下工作.

这是我现在如何做到的(.readline如果没有数据可用,则阻止它):

p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE)
output_str = p.stdout.readline()
Run Code Online (Sandbox Code Playgroud)

python io subprocess nonblocking

477
推荐指数
15
解决办法
21万
查看次数

使用python捕获进程输出的最佳方法是什么?

我正在使用python的subprocess模块来启动一个新进程.我想实时捕获新进程的输出,以便我可以用它做事(显示它,解析它等).我已经看到很多关于如何做到这一点的例子,一些使用自定义文件类对象,一些使用threading,一些尝试读取输出直到进程完成.

文件对象示例(单击我)

  • 我宁愿不使用自定义类文件的对象,因为我想允许用户为提供自己的价值观stdin,stdoutstderr.

线程示例(点击我)

  • 我真的不明白为什么需要线程,所以我不愿意遵循这个例子.如果有人可以解释为什么线程示例有意义我会很高兴听.但是,此示例还限制用户提供自己的值stdoutstderr值.

读取输出示例(见下文)

对我来说最有意义的例子是阅读stdout,stderr直到过程结束.这是一些示例代码:

import subprocess

# Start a process which prints the options to the python program.
process = subprocess.Popen(
    ["python", "-h"],
    bufsize=1,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
)    

# While the process is running, display the output to the user.
while True:

    # Read standard output data.
    for stdout_line in iter(process.stdout.readline, ""):

        # Display standard output data.
        sys.stdout.write(stdout_line)

    # …
Run Code Online (Sandbox Code Playgroud)

python subprocess stdout

5
推荐指数
1
解决办法
1025
查看次数

Python子进程读取

有这个代码

p = subprocess.Popen('tail -f /var/log/syslog', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

for line in p.stdout.readlines():
    print line,
    time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

即使我向syslog添加内容,脚本也会挂起并且不会写任何行.

为什么?

python subprocess

2
推荐指数
1
解决办法
2804
查看次数

标签 统计

python ×3

subprocess ×3

io ×1

nonblocking ×1

stdout ×1