In PyGTK, how can I use a stream?

I have a class that draws a GUI using gtk.

Pressing a button will call a method that will run some external programs.

But the graphical interface may not be redrawn at the same time.

One solution might be to use threads. This example creates a thread outside the GUI class and starts it before calling gtk.main ().

How to create a thread outside the GUI class, define a button click event, and call the appropriate method?

+3
source share
1 answer

, Gtk. , , . , , . "job_aborted" "", .

class MyWindow ...

    # here the button callback
    def on_simulate(self, button):
      self.job_aborted = False
      args = self.makeargs()  # returns a list of command-line args, first is program
      gobject.idle_add(self.job_monitor(args).next)


    def job_monitor(self, args):
       self.state_running()  # disable some window controls
       yield True  # allow the UI to refresh

       # set non-block stdout from the child process
       p  = subprocess.Popen(args, stdout=subprocess.PIPE)
       fd = p.stdout.fileno()
       fl = fcntl.fcntl(fd, fcntl.F_GETFL)
       fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

       while True:

         if self.job_aborted:
           os.kill(p.pid, signal.SIGTERM)
           break

         poll = p.poll()
         if poll is not None:
           break

         try:
           line = p.stdout.readline()
           if line:
              line = line.strip()
              # update display

         except IOError:
           pass

         yield True

       self.state_ready()  # re-enable controls
       if self.job_aborted:
         # user aborted
       else:
         # success!
+4

All Articles