问题描述
我想连续执行多个命令:
I would like to execute multiple commands in a row:
即(只是为了说明我的需要):
i.e. (just to illustrate my need):
cmd
(外壳)
然后
cd 目录
和
ls
并读取ls
的结果.
对 subprocess
模块有什么想法吗?
Any idea with subprocess
module?
更新:
cd dir
和 ls
只是一个例子.我需要运行复杂的命令(遵循特定的顺序,没有任何流水线).事实上,我想要一个子进程 shell 并且能够在它上面启动许多命令.
cd dir
and ls
are just an example. I need to run complex commands (following a particular order, without any pipelining). In fact, I would like one subprocess shell and the ability to launch many commands on it.
推荐答案
有一种简单的方法可以执行一系列命令.
There is an easy way to execute a sequence of commands.
在subprocess.Popen
"command1; command2; command3"
或者,如果您一直使用 Windows,您有多种选择.
Or, if you're stuck with windows, you have several choices.
创建一个临时的.BAT"文件,并将其提供给
subprocess.Popen
在单个长字符串中创建一系列带有\n"分隔符的命令.
Create a sequence of commands with "\n" separators in a single long string.
像这样使用"".
"""
command1
command2
command3
"""
或者,如果你必须做一些零碎的事情,你必须做这样的事情.
Or, if you must do things piecemeal, you have to do something like this.
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()
这将允许您构建一系列命令.
That will allow you to build a sequence of commands.
这篇关于在 Python 中按顺序执行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!