为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

陪伴而非守候 2019-10-19 16:53:35
我试图在Python中找到一种方法来运行其他程序,从而:可以分别记录正在运行的程序的stdout和stderr。可以实时查看正在运行的程序的stdout和stderr,这样,如果子进程挂起,则用户可以看到。(即,我们不等待执行完成才将stdout / stderr打印给用户)奖励标准:正在运行的程序不知道它是通过python运行的,因此不会做意外的事情(例如,将其输出分块而不是实时打印,或者退出,因为它需要一个终端来查看其输出) 。这个小的标准几乎意味着我们将需要使用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 ########## '    print 'STDOUT:'    print stdout    print 'STDOUT:'    print stderr方法2def method2(command):    ## Using pexpect to run our command in a pty, we can see the child's stdout in real-time,    ## however we cannot see the stderr from "curl google.com", presumably because it is not connected to a pty?    ## Furthermore, I do not know how to log it beyond writing out to a file (p.logfile). I need the stdout and stderr    ## as strings, not files on disk! On the upside, pexpect would give alot of extra functionality (if it worked!)    proc = pexpect.spawn('/bin/bash', ['-c', command])    print ' ######### REAL-TIME ######### '    proc.interact()    print ' ########## RESULTS ########## '    ########         Not Possible要尝试这些方法,您需要 import sys,subprocess,pexpectpexpect是纯python,可以与sudo pip安装pexpect我认为解决方案将涉及python的pty模块-这有点像是一种妖术,我找不到任何知道如何使用的人。也许这样就知道了:)作为一个提示,我建议您使用“ curl www.google.com”作为测试命令,因为出于某种原因它会在stderr上显示其状态:D
查看完整描述

3 回答

  • 3 回答
  • 0 关注
  • 1080 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信