相关疑难解决方法(0)

Python在保留顺序的同时分别从子进程stdout和stderr读取

我有一个python子进程,我正在尝试从中读取输出和错误流.目前我有它的工作,但我只能在读完stderr之后阅读stdout.这是它的样子:

process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout_iterator = iter(process.stdout.readline, b"")
stderr_iterator = iter(process.stderr.readline, b"")

for line in stdout_iterator:
    # Do stuff with line
    print line

for line in stderr_iterator:
    # Do stuff with line
    print line
Run Code Online (Sandbox Code Playgroud)

如您所见,stderrfor循环在stdout循环完成之前无法启动.如何修改它以便能够以正确的顺序读取这两行?

澄清:我仍然需要能够判断一条线是否来自stdout或者stderr因为我的代码中它们的处理方式不同.

python subprocess stdout stderr

29
推荐指数
5
解决办法
2万
查看次数

运行命令并像在终端中一样近乎实时地获取它的stdout,stderr

我试图在Python中找到一种方法来运行其他程序:

  1. 正在运行的程序的stdout和stderr可以单独记录.
  2. 正在运行的程序的stdout和stderr可以近乎实时地查看,这样如果子进程挂起,用户就可以看到.(即我们不会在将stdout/stderr打印到用户之前等待执行完成)
  3. 奖励标准:正在运行的程序不知道它是通过python运行的,因此不会做意想不到的事情(比如chunk它的输出而不是实时打印,或退出因为它需要终端查看其输出) .这个小标准几乎意味着我们需要使用我认为的pty.

这是我到目前为止所得到的...方法1:

def method1(command):
    ## subprocess.communicate() will give us the stdout and stderr sepurately, 
    ## but we will have to wait until the end of command execution to print anything.
    ## This means if the child process hangs, we will never know....
    proc=subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, executable='/bin/bash')
    stdout, stderr = proc.communicate() # record both, but no way to print stdout/stderr in real-time
    print ' ######### REAL-TIME ######### '
    ########         Not Possible
    print ' ########## RESULTS ########## …
Run Code Online (Sandbox Code Playgroud)

python subprocess tty pexpect pty

15
推荐指数
1
解决办法
3702
查看次数

标签 统计

python ×2

subprocess ×2

pexpect ×1

pty ×1

stderr ×1

stdout ×1

tty ×1