相关疑难解决方法(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万
查看次数

如何打印和显示subprocess stdout和stderr输出而不失真?

也许在以太中有人可以帮我解决这个问题.(我在SO上已经看到了很多类似的问题,但没有一个涉及标准输出和标准错误或处理与我相似的情况,因此这个新问题.)

我有一个python函数打开一个子进程,等待它完成,然后输出返回代码,以及标准输出和标准错误管道的内容.当进程正在运行时,我还想在填充它们时显示两个管道的输出.我的第一次尝试导致了这样的事情:

process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

stdout = str()
stderr = str()
returnCode = None
while True:
    # collect return code and pipe info
    stdoutPiece = process.stdout.read()
    stdout = stdout + stdoutPiece
    stderrPiece = process.stderr.read()
    stderr = stderr + stderrPiece
    returnCode = process.poll()

    # check for the end of pipes and return code
    if stdoutPiece == '' and stderrPiece == '' and returnCode != None:
        return returnCode, stdout, stderr

    if stdoutPiece != '': print(stdoutPiece)
    if stderrPiece != '': print(stderrPiece) …
Run Code Online (Sandbox Code Playgroud)

python subprocess

8
推荐指数
1
解决办法
3472
查看次数

标签 统计

python ×2

subprocess ×2

io ×1

nonblocking ×1