如何使用子流程Popen Python

问题:如何使用子流程Popen Python

由于os.popen被subprocess.popen取代,我想知道如何转换

os.popen('swfdump /tmp/filename.swf/ -d')

到subprocess.popen()

我试过了:

subprocess.Popen("swfdump /tmp/filename.swf -d")
subprocess.Popen("swfdump %s -d" % (filename))  # NOTE: filename is a variable
                                                # containing /tmp/filename.swf

但是我想我没有正确地写出来。任何帮助,将不胜感激。谢谢

Since os.popen is being replaced by subprocess.popen, I was wondering how would I convert

os.popen('swfdump /tmp/filename.swf/ -d')

to subprocess.popen()

I tried:

subprocess.Popen("swfdump /tmp/filename.swf -d")
subprocess.Popen("swfdump %s -d" % (filename))  # NOTE: filename is a variable
                                                # containing /tmp/filename.swf

But I guess I’m not properly writing this out. Any help would be appreciated. Thanks


回答 0

subprocess.Popen 接受参数列表:

from subprocess import Popen, PIPE

process = Popen(['swfdump', '/tmp/filename.swf', '-d'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()

该文档中甚至有一部分专门用于帮助用户从迁移os.popensubprocess

subprocess.Popen takes a list of arguments:

from subprocess import Popen, PIPE

process = Popen(['swfdump', '/tmp/filename.swf', '-d'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()

There’s even a section of the documentation devoted to helping users migrate from os.popen to subprocess.


回答 1

使用sh,它将使事情变得容易得多:

import sh
print sh.swfdump("/tmp/filename.swf", "-d")

Use sh, it’ll make things a lot easier:

import sh
print sh.swfdump("/tmp/filename.swf", "-d")

回答 2

以最简单的方式使用子流程!

import subprocess
cmd = 'pip install numpy'.split()  #replace with your command
subprocess.call(cmd)

Using Subprocess in easiest way!!

import subprocess
cmd = 'pip install numpy'.split()  #replace with your command
subprocess.call(cmd)