如何在Python中顺序执行命令?
我想要一次性执行多个命令:
比如说(只是为了说明我的需求):
cmd
(也就是命令行)
然后
cd dir
接着
ls
最后读取ls
的结果。
有没有什么方法可以用subprocess
模块实现这个?
更新:
cd dir
和ls
只是个例子。我需要运行一些复杂的命令(按照特定的顺序,不用管道)。实际上,我想要一个子进程的命令行,并且能够在上面启动多个命令。
6 个回答
6
在每个名字里包含'foo'的文件中查找'bar':
from subprocess import Popen, PIPE
find_process = Popen(['find', '-iname', '*foo*'], stdout=PIPE)
grep_process = Popen(['xargs', 'grep', 'bar'], stdin=find_process.stdout, stdout=PIPE)
out, err = grep_process.communicate()
'out'和'err'是字符串对象,分别包含标准输出和可能出现的错误输出。
33
要做到这一点,你需要:
- 在调用
subprocess.Popen
时,添加shell=True
这个参数, - 用以下方式分隔命令:
- 如果是在 *nix 系统的命令行(比如 bash、ash、sh、ksh、csh、tcsh、zsh 等)下运行,就用
;
来分隔命令。 - 如果是在 Windows 的
cmd.exe
下运行,就用&
来分隔命令。
- 如果是在 *nix 系统的命令行(比如 bash、ash、sh、ksh、csh、tcsh、zsh 等)下运行,就用
25
有一种简单的方法可以执行一系列命令。
你可以在 subprocess.Popen
中使用以下内容:
"command1; command2; command3"
如果你在使用Windows系统,还有几种选择。
可以创建一个临时的 ".BAT" 文件,然后把它提供给
subprocess.Popen
。可以把一系列命令用 "\n" 分隔,放在一个长字符串里。
使用 """s,像这样:
"""
command1
command2
command3
"""
如果你必须一步一步来,那你需要像这样做:
class Command( object ):
def __init__( self, text ):
self.text = text
def execute( self ):
self.proc= subprocess.Popen( ... self.text ... )
self.proc.wait()
class CommandSequence( Command ):
def __init__( self, *steps ):
self.steps = steps
def execute( self ):
for s in self.steps:
s.execute()
这样可以让你构建一系列命令。