Snippet: The leanest Popen wrapper

Peter Otten __peter__ at web.de
Wed Aug 3 12:21:22 EDT 2011


Phlip wrote:

> Groupies:

I smell a slight misperception of the audience you are addressing ;)

> This is either a code snippet, if you like it, or a request for a
> critique, if you don't.
> 
> I want to call a command and then treat the communication with that
> command as an object. And I want to do it as application-specifically
> as possible. Anyone could think of a way to productize this:
> 
> def command(*cmdz):
> 
>     process = Popen( flatten(cmdz),
>                      shell= True,
>                      stdout= subprocess.PIPE,
>                      stderr= subprocess.PIPE,
>                      bufsize= 4096 )

Protect your environment, don't let stderr pollute the nearby river ;)

>     def line():
>         return process.stdout.readline().rstrip()
> 
>     def s():
>         while True:
>             l = line()

At that point l may be empty because you have read the output completely or 
because there was an empty line that you rstripped to look like the end of 
file.

>             if not l:  break
>             yield l
> 
>     line.s = s
> 
>     return line

I think you are overdoing that closure/function factory thing a bit...

Seriously, you should reread the subprocess documentation to learn how to 
avoid deadlocks.



More information about the Python-list mailing list