GUI中python中程序的实时输出

时间:2018-12-05 21:08:18

标签: python subprocess gtk3 python-multithreading

我正在使用GTK在python中为命令行程序编写图形外壳。主程序的输出如下:

INSERT INTO tableX 
        (attractionID, customerID, number_of_people, date_of_attraction)
 values ('X', 'Y', '2', '2020-12-01') WHERE UserName = '$UserName'

我有一个开始按钮,可通过子过程启动程序。由于我希望主窗口在启动过程中可操作,因此我使用了thrading。这是我的代码:

Starting Tractor:

Dec 04 22:10:34.000 [notice] Bootstrapped 0%: Starting
Dec 04 22:10:34.000 [notice] Bootstrapped 80%: Connecting to the Tor network
Dec 04 22:10:35.000 [notice] Bootstrapped 85%: Finishing handshake with first hop
Dec 04 22:10:36.000 [notice] Bootstrapped 90%: Establishing a Tor circuit
Dec 04 22:10:37.000 [notice] Bootstrapped 100%: Done
Tractor is conneted.

问题在于日志输出不是实时的,但要等到整个过程完成后才打印整个输出!

我想要当时的实际百分比,以便将其传递到进度条,以显示完成了多少任务。我该怎么办?

编辑

由于theGtknerd,我将代码更改为以下代码,但是feed函数在该过程完成后仍然可以工作,并且只打印整个输出的第一行。我认为这是触发IO_IN时的故障。

def on_start_clicked(self, button):
    spinner = Gtk.Spinner()
    self.props.icon_widget = spinner
    spinner.start()
    self.show_all()
    header_bar = self.get_parent()
    if self.is_running():
        def task_thread():
            task = Popen(command + "stop", stdout=PIPE, shell=True)
            task.wait()
            spinner.stop()
            header_bar.show_progress_button(False)
            self.update_label()
    else:
        def task_thread():
            header_bar.show_progress_button(True)
            task = Popen(command + "start", stdout=PIPE, shell=True)
            while True:
                output = task.stdout.readline().decode("utf-8")
                if output == '' and task.poll() is not None:
                    break
                if output and '%' in output:
                    print(output.split()[5][:-2])
            task.wait()
            spinner.stop()
            self.update_label()

    thread = Thread(target=task_thread)
    thread.daemon = True
    thread.start()

1 个答案:

答案 0 :(得分:1)

这是一个可供您学习的小例子。所以在我的Python文件中,我有:

#!/usr/bin/env python3

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib, GObject
from subprocess import Popen, PIPE, STDOUT
import os, sys


class GUI:
    def __init__(self):

        window = Gtk.Window()
        self.label = Gtk.Label()
        window.add(self.label)
        window.show_all()
        window.connect("destroy", self.on_window_destroy)

        p = Popen(['./long_run.sh'], stdout = PIPE,stderr = STDOUT,stdin = PIPE)
        self.io_id = GObject.io_add_watch(p.stdout, GObject.IO_IN, self.feed)
        GObject.io_add_watch(p.stdout, GObject.IO_HUP, self.thread_finished)

    def feed (self, stdout, condition):
        line = stdout.readline()
        line = line.decode(encoding="utf-8", errors="strict")
        self.label.set_label(line)
        return True

    def thread_finished (self, stdout, condition):
        GObject.source_remove(self.io_id)
        stdout.close()
        self.label.set_label("Hurray, all done!")

    def on_window_destroy(self, window):
        Gtk.main_quit()
        print ("shutdown")

def main():
    app = GUI()
    Gtk.main()

if __name__ == "__main__":
    sys.exit(main())

在long_run.sh文件中,我有:

#!/bin/bash

echo "Loading, please wait..."
sleep 5
echo "10%"
sleep 5
echo "20%"
sleep 5
echo "30%"
sleep 5
echo "40%"
sleep 5
echo "50%"
sleep 5
echo "60%"
sleep 5
echo "70%"
sleep 5
echo "80%"
sleep 5
echo "90%"
sleep 5
echo "100%"
sleep 5