how to use pexpect to get spontaneous output of subprocess in python

我们两清 提交于 2019-12-03 16:13:42

Have you tried something like:

child = pexpect.spawn(launchcmd)
while True:
    try:
        child.expect('\n')
        print(child.before)
    except pexpect.EOF:
        break

I found that these two methods work well for getting live output.

If you don't want the option for user interaction, like in a background process:

child = pexpect.spawn(launchcmd)
child.logfile = sys.stdout
child.expect(pexpect.EOF)
child.close()

If you weren't using a background process and want the ability to interact with the program (if it prompts you). What happens here is that you go into interactive mode and pexpect writes directly to the screen. When the program hits it's end/EOF it throws an OSError.

child = pexpect.spawn(launchcmd)
try:
    child.interact()
except OSError:
    pass
child.close()    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!