如何使用pexpect在python中获得子进程的自发输出 [英] how to use pexpect to get spontaneous output of subprocess in python

查看:338
本文介绍了如何使用pexpect在python中获得子进程的自发输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与我的另一篇帖子有关. wx.TextCtrl出现多线程问题(或底层的GTK +),在通过从主线程调用GUI交互进行更正后,我发现它再次涉及到管道块缓冲问题.那么如何从subprocess.stdout获得自发输出呢?

This is related to my another post multithreading issue with wx.TextCtrl (or underlying GTK+), which after correction with calling GUI interactions from primary thread, I find it again comes to the pipe block buffering problem. so How to get spontaneous output from the subprocess.stdout?

简而言之,当前我正在使用subprocess.popen启动外部长时间运行的程序.

To be in short, currently I am using subprocess.popen to launch an external long-time running program.

    launchcmd=["EXTERNAL_PROGRAM_EXE"]
    p = subprocess.Popen(launchcmd, stdin=subprocess.PIPE, 
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    self.outputThread = BashProcessThread(p.stdout.readline)
    self.outputThread.start()
    # wx.TextCtrl is used to make input/output
    self.textctrl = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER|wx.TE_MULTILINE)

然后我使用一个单独的线程来读取后台程序的标准输出,并使用"wx.CallAfter"进行回调.

And I use a separate thread to read the stdout of the background program, with "wx.CallAfter" to call back.

class BashProcessThread(threading.Thread):
    def __init__(self, readlineFunc, textctrl):
        threading.Thread.__init__(self)
        self.readlineFunc = readlineFunc

    def run(self):
        while True:
           line = self.readlineFunc()
           wx.CallAfter(textctrl.AppendText(line))

上面的代码打印出子进程日志消息的块挂起的块(而不是自发地一行一行地),最糟糕的是,直到用户发送下一行后,剩余的5-6行日志消息才能被及时打印出来.输入.

The above code prints out the subprocess log messages block-hanging-block (instead of spontaneously line by line), and the worst is the remaining 5-6 lines of log messages could not be timely printed until the user send the next input.

从我的旧文章中,我知道有pty和pexpect,这可能使子流程认为它正在与伪tty交互.但是应该如何使用预期,特别是考虑到后台进程是长期的,独立运行的任务呢?

From my old post, I get to know there is pty and pexpect, which could make the subprocess thought it is interacting with pseudo-tty. But how should pexpect be used, especially considering the background process is long-term, independent running task?

例如,如果我使用

child=pexpect.spawn(launchcmd)

如何获取子流程的输出和输入,因此我可以使用wx.TextCtrl打印输出,还可以使用wx.TextCtrl将用户输入转发到子流程?

How can I get the output and input of the subprocess, so I could use wx.TextCtrl to print the output, and also use wx.TextCtrl to forward user input to subprocess?

推荐答案

您是否尝试过以下方法:

Have you tried something like:

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

这篇关于如何使用pexpect在python中获得子进程的自发输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆