避免管道破裂子流程.Popen以及多个不同的请求

2024-10-02 18:26:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个多线程python脚本,其中我有一个专门的线程负责执行一些shell命令,而不需要重新打开一个全新的zshshell,但保持同一个会话仍然有效。在

主线程将要执行的命令放入队列中,队列与负责执行命令的线程共享。在

import threading, Queue
class ShellThread(threading.Thread):
    def __init__(self, command_q, command_e):
        super(ShellThread, self).__init__()
        self.command_q = command_q
        self.command_e = command_e
        self.stoprequest = threading.Event()

        from subprocess import Popen, PIPE
        import os
        self.zsh = Popen("zsh", stdin=PIPE, stdout=PIPE)

    def run(self):
        while not self.stoprequest.isSet():
            try:
                command = self.command_q.get(True, 0.1)
                print "ShellThread is now executing command : " + command
                self.zsh.stdin.write(command + '\n')
                self.zsh.stdin.flush()
                self.command_e.set()

            except Queue.Empty:
                continue

    def join(self, timeout=None):
        self.stoprequest.set()
        self.zsh.stdin.close()
        super(ShellThread, self).join(timeout)

def main(args):
    __command_q = Queue.Queue()
    __command_e = threading.Event()
    __thread = ShellThread(command_q=__command_q, command_e=__command_e)
    __thread.start()

    while 1:
        line = raw_input()
        print 'MainThread : ' + line
        __command_q.put(line)
        __command_e.wait(0.5)
        __command_e.clear()

if __name__ == '__main__':
    import sys
    main(sys.argv[1:])

它确实有效,但是我有随机的IOError: [Errno 32] Broken pipe错误,而且我仍然没有找到在执行每个命令之后获得stdout的方法。在

更新: 请注意,这样做的全部目的是保持一个并且只有zshshell处于打开状态(这就是为什么我有一个专用线程用于此目的)以便及时运行不同的命令。 我不能使用Popen.communicate,因为它会在命令结束后关闭shell,而且我不知道我必须预先运行的所有命令。在


Tags: import命令selfqueuemaindefstdinline