有没有一种方法可以通过Popen执行命令行并返回结果?
command = Popen(['ls', '-l'])
我怎样从命令对象中获得ls -l
?我使用的是Python 2.7。
command = Popen(['ls', '-l'])
我怎样从命令对象中获得ls -l
?我使用的是Python 2.7。
如果您正在使用Python 3,则command.args
是最简单的方法:
from subprocess import Popen
command = Popen(['ls', '-l'])
print command.args
输出:
['ls', '-l']
对于python-2.7,参数的存储方式与3.3版本不同。您需要记住它们或者想出一个解决方法。
其中一种方法是编写自己的继承自Popen
的类或者简单地编写一个Popen
的包装器:
from subprocess import _Popen
def Popen(*args, **kwds):
res = _Popen(*args, **kwds)
if not hasattr(res, "args"):
res.args = args[0]
return res
args
属性没有被使用,但之后被使用了,因此您可能需要像上面示例中所示的那样进行保护。from sys import version
import subprocess
class Popen(subprocess.Popen):
def __init__(self, *args, **kwds):
subprocess.Popen.__init__(self, *args, **kwds)
self.args = args[0]
if version[0] < 3 or (version[0]==3 and version[1] < 3): # pre 3.3
subprocess.Popen = Popen
我有时候就是这样做的!
import subprocess,
cmd = ["ls", "-a" ]
proc = subprocess.Popen(cmd, stdout = subprocess.PIPE)
stdout = proc.communicate()[0]