python - 使用 python Gtk 在 gui 窗口中显示终端输出

标签 python gtk

我正在开发一个程序,我想要一个窗口来显示终端抛出的输出(就像包管理器那样)。例如,如果我给出安装命令,安装过程应该输出到我的窗口而不是终端。有没有办法在 python Gtk 中做到这一点?

我使用的是 Ubuntu 13.04。

最佳答案

如果您使用的是 Linux(如您所说),则类似这样的方法应该有效:

import gtk 
import gobject
import pango
import os
from subprocess import Popen, PIPE
import fcntl

wnd = gtk.Window()
wnd.set_default_size(400, 400)
wnd.connect("destroy", gtk.main_quit)
textview = gtk.TextView()
fontdesc = pango.FontDescription("monospace")
textview.modify_font(fontdesc)
scroll = gtk.ScrolledWindow()
scroll.add(textview)
exp = gtk.Expander("Details")
exp.add(scroll)
wnd.add(exp)
wnd.show_all()
sub_proc = Popen("ping -c 10 localhost", stdout=PIPE, shell=True)
sub_outp = ""


def non_block_read(output):
    fd = output.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    try:
        return output.read().decode("utf-8")
    except:
        return ''


def update_terminal():
    textview.get_buffer().insert_at_cursor(non_block_read(sub_proc.stdout))
    return sub_proc.poll() is None

gobject.timeout_add(100, update_terminal)
gtk.main()

非阻塞读思路来自here .

使用标签显示文本:

import gtk 
import gobject
import os
from subprocess import Popen, PIPE
import fcntl

wnd = gtk.Window()
wnd.set_default_size(400, 400)
wnd.connect("destroy", gtk.main_quit)
label = gtk.Label()
label.set_alignment(0, 0)
wnd.add(label)
wnd.show_all()
sub_proc = Popen("ping -c 10 localhost", stdout=PIPE, shell=True)
sub_outp = ""


def non_block_read(output):
    ''' even in a thread, a normal read with block until the buffer is full '''
    fd = output.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    try:
        return output.read().decode("utf-8")
    except:
        return ''


def update_terminal():
    label.set_text(label.get_text() + non_block_read(sub_proc.stdout))
    return sub_proc.poll() is None

gobject.timeout_add(100, update_terminal)
gtk.main()

关于python - 使用 python Gtk 在 gui 窗口中显示终端输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17038063/

相关文章:

python - 给定一个输出列表的函数,Python 是否可以为每个组件提取一个函数?

c++ - 在 gtk3 Textview 中显示字符串时出现问题

python - Gtk 在添加和删除列表框行时崩溃

c - 如何发送多个条目到函数 - GTK

python - 由于 EXTENSION 数组为空,PIL 的保存功能中出现“未知扩展名”

python - 几天不活动后,Django Allauth 似乎将用户注销

python - Scrapy:如何将爬行统计信息保存到json文件?

c++ - 如何使用 GStreamer 和 XOverlay 在 GTK+ 应用程序窗口中嵌入视频?

c - GTK 不呈现所有用户界面

python - 带有列表的字典 : Fastest way to get the key corresponding to the minimum value of the fourth list item?