简体   繁体   中英

How do I translate Ruby's IO.popen calls into Python's subprocess.Popen calls?

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?

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())
import subprocess

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM