Direct interaction with subprocess - the curse of blocking I/O

yam850 kurt.alfred.mueller at gmail.com
Fri Jul 3 05:38:48 EDT 2009


On 1 Jul., 21:30, spillz <damienlmo... at gmail.com> wrote:
> On Jun 29, 3:15 pm, Pascal Chambon <chambon.pas... at gmail.com> wrote:
> > I've had real issues with subprocesses recently : from a python script,
> > on windows, I wanted to "give control" to a command line utility, i.e
> > forward user in put to it and display its output on console. It seems
> > simple, but I ran into walls :
> If you are willing to have a wxPython dependency, wx.Execute handles
> non-blockingi/o with processes on all supported platforms

I made a python method/function for non blocking read from a file
object.
I use it in one of my python programs.
When looking at the code bear in mind that I am not an expert and I am
happy to see comments.

#------------------------------------------------------------------
def non_blocking_readline(f_read=sys.stdin, timeout_select=0.0):
    """to readline non blocking from the file object 'f_read'
       for 'timeout_select' see module 'select'"""
    import select
    text_lines = ''                       # empty string
    while True:                           # as long as there are bytes
to read
        try:                              # try select
            rlist, wlist, xlist = select.select([f_read], [], [],
timeout_select)
        except:                           # select ERROR
            print >>sys.stderr, ("non_blocking_read select ERROR")
            break
        if DEBUG: print("rlist=%s, wlist=%s, xlist=%s" % (repr(rlist),
repr(wlist), repr(xlist)))
        if  len(rlist) > 0:
            text_read = f_read.readline() # get a line
            if DEBUG: print("after read/readline text_read:'%s', len=
%s" % (text_read, repr(len(text_read))))
            if  len(text_read) > 0:       # there were some bytes
                text_lines = "".join([text_lines, text_read])
                if DEBUG: print("text_lines:'%s'" % (text_lines))
            else:
                break                     # there was no byte in a
line
        else:
            break                         # there was no byte in the
f_read
    if  text_lines  ==  '':
        return None
    else:
        return text_lines


--
Kurt



More information about the Python-list mailing list