Python, Quickly and Glade, showing stdout in a Tex

2019-07-22 21:15发布

问题:

I've spent ages looking for a way to do this, and I've so far come up with nothing. :(

I'm trying to make a GUI for a little CLI program that I've made - so I thought using Ubuntu's "Quickly" would be the easiest way. Basically it appears to use Glade for making the GUI. I know that I need to run my CLI backend in a subprocess and then send the stdout and stderr to a textview. But I can't figure out how to do this.

This is the code that Glade/Quickly created for the Dialog box that I want the output to appear into:

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()

If I put this in the finish_initializing function

backend_process = subprocess.Popen(["python", <path to backend>], stdout=subprocess.PIPE, shell=False)

then the process starts and runs as another PID, which is what I want, but now how do I send backend_process.stdout to the TextView? I can write to the textview with:

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.

回答1:

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

You could use GObject.io_add_watch to monitor the subprocess output or create a separate thread to read from the subprocess.

# 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)

Or using a thread:

# 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.