相关疑难解决方法(0)

运行命令并像在终端中一样近乎实时地获取它的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
查看次数

标签 统计

pexpect ×1

pty ×1

python ×1

subprocess ×1

tty ×1