views:

164

answers:

2

I've read the documentation and I've tried lots of things in the REPL, and Googled, but I can't for the life of me understand how subprocess.Popen works in Python.

Here is some Ruby code I am using:

IO.popen("some-process") do |io|
  while(line = io.gets)
    # do whatever with line
  end
end

How do I translate this into Python using subprocess.Popen?

+2  A: 

Probably the simplest "close relative" of your Ruby code in Python:

>>> import subprocess
>>> io = subprocess.Popen('ls', stdout=subprocess.PIPE).stdout
>>> for line in io: print(line.strip())
Alex Martelli
Note that reading from a `Popen`'s `stdout` carries some risk of deadlocks. It's generally preferred to use `communicate` if blocking is acceptable.
Mike Graham
@Mike, if the subprocess just closes its stdin first thing (as `ls` does -- as `some-process` had better do in the Ruby code since it's **never** given **any** input!) no deadlock is possible in any OS I know of. Only subprocesses that **use** their stdin are at any conceivable risk -- so your "generally" is just totally inapplicable to both this Q and my A.
Alex Martelli
+1  A: 
import subprocess

process = subprocess.Popen(['ls',], stdout=subprocess.PIPE)
print process.communicate()[0]
Corey Goldberg