Can read() be non-blocking?

一首诗 newptcai at gmail.com
Thu Nov 6 23:10:45 EST 2008


On Nov 7, 6:54 am, Thomas Christensen <thom... at thomaschristensen.org>
wrote:
> This issue has been raised a couple of times I am sure.  But I have yet
> to find a satisfying answer.
>
> I am reading from a subprocess and this subprocess sometimes hang, in
> which case a call to read() call will block indefinite, keeping me from
> killing it.
>
> The folloing sample code illustrates the problem:
>
>   proc = subprocess.Popen(['/usr/bin/foo', '/path/to/some/file'],
>                           stdout=subprocess.PIPE)
>   output = StringIO.StringIO()
>   while True:
>       r = select.select([proc.stdout.fileno()], [], [], 5)[0]
>       if r:
>           # NOTE: This will block since it reads until EOF
>           data = proc.stdout.read()
>           if not data:
>               break  # EOF from process has been reached
>           else:
>               output.write(data)
>       else:
>           os.kill(proc.pid, signal.SIGKILL)
>   proc.wait()
>
>   <Process the output...>
>
> As the NOTE: comment above suggests the call to read() will block here.
>
> I see two solutions:
>
> 1. Read one byte at a time, meaning call read(1).
> 2. Read non-blocking.
>
> I think reading one byte at a time is a waste of CPU, but I cannot find
> a way to read non-blocking.
>
> Is there a way to read non-blocking?  Or maybe event a better way in
> generel to handle this situation?
>
> Thanks
>
>                 Thomas

As far as I know, you can use '''fctnl''' to make a file handle non-
blocking.

But :

1. I don't know if it works on standard io
2. If it works in python



More information about the Python-list mailing list