我试图搜索,但似乎没有任何效果。例如:
我目前正在使用PyGTK在Python2.7中编写简单的通信应用程序。我有后台进程,就像那样在while循环中监听套接字。当我收到表单服务器时,我想显示消息。但是当我启动gtk.main()时,它显然会再次循环,所以我的监听循环不起作用。我需要为每条消息显示新窗口或关闭旧窗口并显示包含所有未读消息的新窗口。我可以以某种方式显示窗口(或多个窗口)并且不会阻止我的监听循环吗?
IOChannel解决方案
while True: #listening loop
print 'Start'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.bind((socket.gethostname(), 80))
sock.listen(2)
conn, address = sock.accept()
conn.sendall('200 OK')
fd = conn.fileno() #Make file descriptor from socket
gio_channel = glib.IOChannel(fd) #Pass it to IOChannel
if(new_message):
#display message with gtk.main()
else
#Do something else like update file
subprocess.Popen解决方案
while True: #listening loop
print 'Start'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.bind((socket.gethostname(), 80))
sock.listen(2)
conn, address = sock.accept()
conn.sendall('200 OK')
all_json = conn.recv(2048)
if(new_message):
# This script run pygtk app in the background
subprocess.Popen(['python', 'communication_app.py'])
else
#Do something else like update file
答案 0 :(得分:0)
您可能想尝试使用GLib的GIOChannel
(Python文档中的GLib.IOChannel)来处理作为事件源(GSource
)的套接字。然后使用g_io_create_watch
(Python中的GLib.IOChannel.add_watch
)集成到GTK +主循环中。
Gio
库中还有许多更高级的套接字处理内容: