Source

green380 / examples / child_proc.py

from fcntl import fcntl, F_SETFL
from gthread import Event, spawn, run
from os import O_NONBLOCK
from signal import SIGCHLD
from subprocess import Popen, PIPE

def find_var():
    sigchld = Event('signal', SIGCHLD)
    proc = Popen(['find', '/var'], stdout=PIPE, stderr=PIPE)
    stdout = Event('read', proc.stdout)
    stderr = Event('read', proc.stderr)
    fcntl(proc.stdout, F_SETFL, O_NONBLOCK)
    lines = 0
    stderr_buf = b''
    while any([sigchld, stdout, stderr]):
        event = yield
        if event is sigchld:
            rc = proc.poll()
            if rc is not None:
                print('process terminated with returncode', rc)
                sigchld.remove()
        elif event is stdout:
            buf = proc.stdout.read(100)
            #~ print(buf)
            if buf:
                lines += buf.count(b'\n')
            else:
                stdout.remove()
                print('got', lines, 'lines')
        elif event is stderr:
            buf = proc.stderr.read(1)
            if not buf:
                stderr.remove()
            stderr_buf += buf

spawn(find_var)
run()