如何使用urwid和asyncio进行长时间无阻塞的任务?

时间:2018-02-22 15:26:57

标签: linux python-3.5 nonblocking urwid

我正在编写一个Python curses应用程序,它通过在进程中发送和接收字符串来控制外部(Linux,如果有帮助)进程。分别为stdinstdout。界面使用urwid。我已经编写了一个类来控制外部进程,还有一些用于编写一些urwid组件。

我还有一个按钮,可以向外部进程发送命令。但是,该过程不会立即响应,其任务通常需要几秒钟,在此期间我不希望界面冻结。

这是我如何运行子进程:

def run(self, args):
    import io, fcntl, os
    from subprocess import Popen, PIPE

    # Run wpa_cli with arguments, use a thread to feed the process with an input queue
    self._pss = Popen(["wpa_cli"] + args, stdout=PIPE, stdin=PIPE)
    self.stdout = io.TextIOWrapper(self._pss.stdout, encoding="utf-8")
    self.stdin = io.TextIOWrapper(self._pss.stdin, encoding="utf-8", line_buffering=True)

    # Make the process' stdout a non-blocking file
    fd = self.stdout.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    ...

我必须完成这个过程'输出流非阻塞,以便能够解析其输出。我不知道这对我的问题是否重要。

这是我用来控制子进程输入和输出流的方法:

def read(self, parser=None, transform=None, sentinel='>'):
    """ Reads from the controlled process' standard output until a sentinel
    is found. Optionally execute a callable object with every line. Parsed
    lines are placed in a list, which the function returns upon exiting. """

    if not transform:
        transform = lambda str: str

    def readline():
        return transform(self.stdout.readline().strip())

    # Keep a list of (non-empty) parsed lines
    items = []
    for line in iter(readline, sentinel):
        if callable(parser):
            item = parser(line)
            if item is not None:
                items.append(item)
    return items

def send(self, command, echo=True):
    """ Sends a command to the controlled process. Action commands are
    echoed to the standard output. Argument echo controls whether or not
    they're removed by the reader function before parsing. """

    print(command, file=self.stdin)

    # Should we remove the echoed command?
    if not echo:
        self.read(sentinel=command)

我所谈到的按钮只是从主脚本入口函数设置了回调。该回调应该向子进程发送命令并循环通过结果输出行,直到找到给定的文本,在这种情况下回调函数退出。在此之前,该过程会输出一些我需要捕获并在用户界面中显示的有趣信息。

例如:

def button_callback():
    # This is just an illustration

    filter = re.compile('(event1|event2|...)')

    def formatter(text):
        try:
            return re.search(filter, text).group(1)
        except AttributeError:
            return text

    def parser(text):
        if text == 'event1':
            # Update the info Text accordingly
        if text == 'event2':
            # Update the info Text accordingly

    controller.send('command')
    controller.read(sentinel='beacon', parser=parser, transform=formatter)

需要注意的是:

  • read()函数旋转(我无法找到另一种方法),即使进程输出流是静默的,直到从(可选)解析的行读取sentinel值,
  • urwid界面不会刷新,直到退出按钮回调功能,这会阻止urwid主循环刷新屏幕。

我可以使用一个帖子,但是从我读过的urwid支持asyncio以及我想要实现的内容。你可以叫我愚蠢,因为我无法清楚地知道在浏览urwid asyncio示例和阅读Python asyncio文档之后的情况。

考虑到有改变任何这些方法的空间,我仍然希望保持流程控制类 - 即包含read()send()的方法 - 尽可能通用。

到目前为止,我所尝试的一切都没有导致在进程繁忙时更新接口。接收过程的组件' "通知"是一个简单的urwid.Text()小部件。

1 个答案:

答案 0 :(得分:1)

首先要做的两件事:

  • 你不一定需要asyncio与urwid做异步内容,因为它已经有一个simple event loop,它通常足够好,它有处理许多IO场景的原语。

  • 在编写异步代码时,你需要注意编写同步代码,就像那些函数循环一样,直到它找到一个sentinel值,因为它会阻止任何其他代码(包括事件循环本身)执行:这意味着UI将冻结,直到该函数返回

对于您的情况,您可以使用默认的简单事件循环并使用MainLoop.watch_pipe方法,这会创建一个准备在子进程中使用的管道(已经将其置于异步/非阻塞模式, btw :))并在有新数据写入管道时调用回调。

这是一个使用它的简单示例,显示了shell命令的输出,同时保持UI不被阻止(注意,使用一些全局变量,因为懒惰):

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function, absolute_import, division
import subprocess
import urwid


def show_or_exit(key):
    if key in ('q', 'Q', 'esc'):
        raise urwid.ExitMainLoop()


def update_text(read_data):
    text.set_text(text.text + read_data)


def enter_idle():
    loop.remove_watch_file(pipe.stdout)


if __name__ == '__main__':
    widget = urwid.Pile([
        urwid.Button('Here is a button'),
        urwid.Button('And here another button'),
        urwid.Button('One more, just to be sure'),
        urwid.Button("Heck, let's add yet another one!"),
    ])
    text = urwid.Text('PROCESS OUTPUT:\n')
    widget = urwid.Columns([widget, text])
    widget = urwid.Filler(widget, 'top')

    loop = urwid.MainLoop(widget, unhandled_input=show_or_exit)
    stdout = loop.watch_pipe(update_text)
    stderr = loop.watch_pipe(update_text)
    pipe = subprocess.Popen('for i in $(seq 50); do echo -n "$i "; sleep 0.5; done',
                            shell=True, stdout=stdout, stderr=stderr)
    loop.run()

请注意回调update_text中的代码没有理由阻止:它获取已读取的数据,更新组件及其中的内容。没有在循环等待其他事情发生时。

在您的情况下,您可能需要调整解析wpa_cli输出的函数,以便它们也没有理由阻止。例如,在找到值之前,他们可以设置一些变量或以其他方式发出信号,而不是等待循环,而不是有趣的哨兵值。

我希望这是有道理的,请告诉我你是否需要澄清一些事情! :)