Python,Quickly 和 Glade,在 TextView 中显示标准输出

标签 python ubuntu gtk textview subprocess

我花了很长时间寻找一种方法来做到这一点,但到目前为止我一无所获。 :(

我正在尝试为我制作的一个小 CLI 程序制作一个 GUI——所以我认为使用 Ubuntu 的“快速”将是最简单的方法。基本上它似乎使用 Glade 来制作 GUI。我知道我需要在子进程中运行我的 CLI 后端,然后将 stdout 和 stderr 发送到 textview。但我无法弄清楚如何做到这一点。

这是 Glade/Quickly 为我希望输出出现的对话框创建的代码:

from gi.repository import Gtk # pylint: disable=E0611

from onice_lib.helpers import get_builder

import gettext
from gettext import gettext as _
gettext.textdomain('onice')

class BackupDialog(Gtk.Dialog):
    __gtype_name__ = "BackupDialog"

    def __new__(cls):
        """Special static method that's automatically called by Python when 
        constructing a new instance of this class.

        Returns a fully instantiated BackupDialog object.
        """
        builder = get_builder('BackupDialog')
        new_object = builder.get_object('backup_dialog')
        new_object.finish_initializing(builder)
        return new_object

    def finish_initializing(self, builder):
        """Called when we're finished initializing.

        finish_initalizing should be called after parsing the ui definition
        and creating a BackupDialog object with it in order to
        finish initializing the start of the new BackupDialog
        instance.
        """
        # Get a reference to the builder and set up the signals.
        self.builder = builder
        self.ui = builder.get_ui(self)

        self.test = False

    def on_btn_cancel_now_clicked(self, widget, data=None):
        # TODO: Send SIGTERM to the subprocess
        self.destroy()

if __name__ == "__main__":
    dialog = BackupDialog()
    dialog.show()
    Gtk.main()

如果我把它放在 finish_initializing 函数中
backend_process = subprocess.Popen(["python", <path to backend>], stdout=subprocess.PIPE, shell=False)

然后进程启动并作为另一个 PID 运行,这正是我想要的,但现在如何将 backend_process.stdout 发送到 TextView?我可以通过以下方式写入 textview:
BackupDialog.ui.backup_output.get_buffer().insert_at_cursor("TEXT")

但我只需要知道每次有新的标准输出行时如何调用它。

最佳答案

But I just need to know how to have this be called each time there is a new line of stdout.



您可以使用 GObject.io_add_watch监视子进程的输出或创建一个单独的线程来从子进程中读取。
# read from subprocess
def read_data(source, condition):
    line = source.readline() # might block
    if not line:
        source.close()
        return False # stop reading
    # update text
    label.set_text('Subprocess output: %r' % (line.strip(),))
    return True # continue reading
io_id = GObject.io_add_watch(proc.stdout, GObject.IO_IN, read_data)

或使用线程:
# read from subprocess in a separate thread
def reader_thread(proc, update_text):
    with closing(proc.stdout) as file:
        for line in iter(file.readline, b''):
            # execute update_text() in GUI thread
            GObject.idle_add(update_text, 'Subprocess output: %r' % (
                    line.strip(),))

t = Thread(target=reader_thread, args=[proc, label.set_text])
t.daemon = True # exit with the program
t.start()

Complete code examples .

关于Python,Quickly 和 Glade,在 TextView 中显示标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15330419/

相关文章:

python - 将模式保存/加载匹配器作为新的管道组件

python - 通过代理通过 python 连接到保管箱

multithreading - boost::asio::strand 在 Ubuntu 11.04 (boost_all_dev 1.42) 上是否损坏

python-3.x - 我可以在 ubuntu 18.04 中安装 python 3.7 而系统中没有 python 3.6 吗?

python - Pandas 中的分组和求和

Python:为列表中的所有元素添加相同的前缀

python - 使用python将日期中的整数转换为月份名称

python - 如何在glade-3中显示2D numpy数组?

python - 如何解决 GTK 文件选择器对话框中的这个错误

c - 如何禁用 GtkColorButton?