How to run an infinite while loop in pygtk?

梦想的初衷 提交于 2020-01-05 07:01:09

问题


I am creating an application in pygtk which involves running an infinite loop. The loop, I think, interferes witk gtk.main() and hence the application does not respond. Actually, I am building a server-type application which continuously listens for client connections.Plzzz help....I am a newbie in this.

This is a sample of what I was initially trying to do.(For those who wanted the code)

while 1:
  s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  s.bind(('',2727))
  s.listen(1)
  c,d=s.accept()
  print d
  x=c.recv(1024)

I thougth of replacing the gtk.main() in the end with:

while 1:
  s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  s.bind(('',2727))
  s.listen(1)
  s.accept()
  gtk.main_iteration_do(False)

It would work but the s.accept() causes the same problem as earlier....Can somebody help


回答1:


You can force your application to process pending gtk events the following way:

while True:
    #your code 

    while gtk.events_pending():
        gtk.main_iteration()

However, if 'your code' takes a while to execute you should consider implementing it in a background process.




回答2:


You could use a second thread (docs.python.org/library/threading.html). There is also a way incorporate gtk in your loop (by using pygtk.org/docs/pygtk/…) but since you mention networking I guess you are using blocking calls that will also block the loop until something happens on the network. However I can only guess until you show us some actual code.




回答3:


Even without seeing any code, I am pretty sure I know where this question is going. pygtk is probably no different than the other GUI frameworks in that its main loop is an event loop. All widgets in the application register their events to this loop for your app to function. In these event driven GUI frameworks, you should NEVER block the main thread. All operations in the main thread should return relatively quick.

When you need to perform something that is going to block or perform a great deal of processing, this functionality should be moved to a separate thread. This would be needed if your network loop is going to block forever in its own event loop. If this is the case, you would have no option but to use a thread.

I am not specifically familiar with pygtk, but PyQt/PySide provide a function that lets you tell the event loop to process. You can stick this inside of a loop that you are performing in your main thread to periodically flush the events. This would be an alternative to running your process in another thread. But again, only if your other code does not block, and simply loops over and over.



来源:https://stackoverflow.com/questions/10064925/how-to-run-an-infinite-while-loop-in-pygtk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!