用Popen模仿glib.spawn_async ...

时间:2016-09-07 07:48:45

标签: python multithreading gtk glib python-asyncio

函数glib.spawn_async允许您挂钩三个回调,这些回调在stdoutstderr上的事件和过程完成时调用。

如何使用线程或asyncio与subprocess模仿相同的功能?

我对功能而不是线程/ asynio更感兴趣,但包含两者的答案将获得赏金。

这是一个玩具程序,显示我想要做的事情:

import glib
import logging
import os
import gtk


class MySpawn(object):
    def __init__(self):
        self._logger = logging.getLogger(self.__class__.__name__)

    def execute(self, cmd, on_done, on_stdout, on_stderr):
        self.pid, self.idin, self.idout, self.iderr = \
            glib.spawn_async(cmd,
                             flags=glib.SPAWN_DO_NOT_REAP_CHILD,
                             standard_output=True,
                             standard_error=True)
        fout = os.fdopen(self.idout, "r")
        ferr = os.fdopen(self.iderr, "r")
        glib.child_watch_add(self.pid, on_done)
        glib.io_add_watch(fout, glib.IO_IN, on_stdout)
        glib.io_add_watch(ferr, glib.IO_IN, on_stderr)
        return self.pid


if __name__ == '__main__':
    logging.basicConfig(format='%(thread)d %(levelname)s:  %(message)s',
                        level=logging.DEBUG)
    cmd = '/usr/bin/git ls-remote https://github.com/DiffSK/configobj'.split()

    def on_done(pid, retval, *args):
        logging.info("That's all folks!…")

    def on_stdout(fobj, cond):
        """This blocks which is fine for this toy example…"""
        for line in fobj.readlines():
            logging.info(line.strip())
        return True

    def on_stderr(fobj, cond):
        """This blocks which is fine for this toy example…"""
        for line in fobj.readlines():
            logging.error(line.strip())
        return True

    runner = MySpawn()
    runner.execute(cmd, on_done, on_stdout, on_stderr)
    try:
        gtk.main()
    except KeyboardInterrupt:
        print('')

我应该补充说,由于readlines()阻塞,上面将缓冲所有输出并立即发送。如果这不是你想要的,那么你必须使用readline()并确保在命令结束时你读完了之前没有读过的所有行。

1 个答案:

答案 0 :(得分:5)

asyncio有subprocess_exec,根本不需要使用子进程模块:

import asyncio

class Handler(asyncio.SubprocessProtocol):
    def pipe_data_received(self, fd, data):
        # fd == 1 for stdout, and 2 for stderr
        print("Data from /bin/ls on fd %d: %s" % (fd, data.decode()))

    def pipe_connection_lost(self, fd, exc):
        print("Connection lost to /bin/ls")

    def process_exited(self):
        print("/bin/ls is finished.")

loop = asyncio.get_event_loop()
coro = loop.subprocess_exec(Handler, "/bin/ls", "/")

loop.run_until_complete(coro)
loop.close()

使用子进程和线程,它也很简单。您可以为每个管道生成一个线程,并为该过程生成一个wait()

import subprocess
import threading

class PopenWrapper(object):
    def __init__(self, args):
       self.process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.DEVNULL)

       self.stdout_reader_thread = threading.Thread(target=self._reader, args=(self.process.stdout,))
       self.stderr_reader_thread = threading.Thread(target=self._reader, args=(self.process.stderr,))
       self.exit_watcher = threading.Thread(target=self._exit_watcher)

       self.stdout_reader_thread.start()
       self.stderr_reader_thread.start()
       self.exit_watcher.start()

    def _reader(self, fileobj):
        for line in fileobj:
            self.on_data(fileobj, line)

    def _exit_watcher(self):
        self.process.wait()
        self.stdout_reader_thread.join()
        self.stderr_reader_thread.join()
        self.on_exit()

    def on_data(self, fd, data):
        return NotImplementedError

    def on_exit(self):
        return NotImplementedError

    def join(self):
        self.process.wait()

class LsWrapper(PopenWrapper):
    def on_data(self, fd, data):
        print("Received on fd %r: %s" % (fd, data))

    def on_exit(self):
        print("Process exited.")


LsWrapper(["/bin/ls", "/"]).join()

但是,请注意,glib 使用线程来异步执行回调。它使用事件循环,就像asyncio一样。我们的想法是,程序的核心是一个循环,等待某些事情发生,然后同步执行相关的回调。在您的情况下,该数据可用于读取其中一个管道"和"子流程已退出"。一般来说,它也像#X; X11服务器报告鼠标移动","传入的网络流量"等等。你可以通过以下方式模仿glib的行为编写自己的事件循环。在两个管道上使用select module。如果选择报告管道是可读的,但read没有返回数据,则可能退出该过程 - 在这种情况下调用子进程对象上的poll()方法以检查它是否已完成,并调用退出如果它有回调,或者是其他错误回调。