简体   繁体   English

将流I / O添加到Python / GTK 3 GUI

[英]Add stream I/O to a Python/GTK 3 GUI

My Python program has a GUI written in GTK 3 (I'm using GTK 3 via from gi.repository import Gtk ). 我的Python程序有一个用GTK 3编写的GUI(我正在通过from gi.repository import Gtk使用GTK 3)。 I call Gtk.main() to run the GUI. 我调用Gtk.main()来运行GUI。 In addition to running the GUI, the program should constantly monitor standard input for incoming commands and write responses to standard output. 除了运行GUI外,程序还应不断监视标准输入中的输入命令,并将响应写入标准输出中。

What's the proper way to do this with GTK 3 in Python? 用Python中的GTK 3执行此操作的正确方法是什么? Is there some way to hook a stdin listener onto Gtk.main() ? 有什么方法可以将stdin侦听器连接到Gtk.main()吗? Can I use Python's standard I/O API to read from sys.stdin and write to sys.stdout or do I need to use some equivalent Glib API? 我可以使用Python的标准I / O API来读取sys.stdin并写入sys.stdout还是需要使用某些等效的Glib API? Can I just write my responses to stdout or do I need to care about buffering and hook my output code to some Glib I/O abstraction? 我可以只写对stdout的响应,还是需要关心缓冲并将输出代码挂钩到某些Glib I / O抽象?

I managed to scrape together a very basic script: 我设法拼凑出一个非常基本的脚本:

import os
import sys

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GLib, Gtk

logfile = open(os.path.splitext(__file__)[0]+'.log', 'w')

def on_stdin(fobj, cond):
    line = fobj.readline()
    print(repr(line), file=logfile)
    if line == '':
        sys.exit(0)
    return True

win = Gtk.Window()
win.connect('delete-event', Gtk.main_quit)
win.show_all()
GLib.io_add_watch(sys.stdin, GLib.IO_IN, on_stdin)
Gtk.main()

Try piping ls to it. 尝试将ls管道输送到它。 if line == '' is important: if the stream is ready to be read and the read doesn't return any bytes, that means end-of-file. if line == ''很重要:如果流已准备好被读取并且读取未返回任何字节,则意味着文件结束。 If we don't stop watching the stream on end-of-file, we'll get an endless barrage of calls to on_stdin because Unix considers an end-of-file stream always ready for reading (see Why does poll keep returning although there is no input? ) 如果我们不停止在文件末尾观看流,则会收到对on_stdin的无休止的调用,因为Unix认为文件末尾流总是可以读取的(请参阅为什么poll会继续返回,尽管在那里没有输入吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM