Mec*_*urS 20 python windows subprocess
我想连续执行多个命令:
即(只是为了说明我的需要):
cmd(外壳)
然后
cd dir
和
LS
并阅读ls的结果.
有什么想法与子进程模块?
更新:
cd dir和ls只是一个例子.我需要运行复杂的命令(遵循特定的顺序,没有任何流水线操作).实际上,我想要一个子进程shell并能够在其上启动许多命令.
tzo*_*zot 26
要做到这一点,你必须:
shell=True
在subprocess.Popen
通话中提供参数,并且;
如果在*nix shell下运行(bash,ash,sh,ksh,csh,tcsh,zsh等)&
如果在cmd.exe
Windows 下运行S.L*_*ott 20
有一种简单的方法来执行一系列命令.
请使用以下内容 subprocess.Popen
"command1; command2; command3"
Run Code Online (Sandbox Code Playgroud)
或者,如果你遇到了Windows,你有几种选择.
创建一个临时的".BAT"文件,并将其提供给 subprocess.Popen
使用单个长字符串中的"\n"分隔符创建一系列命令.
使用"",就像这样.
"""
command1
command2
command3
"""
Run Code Online (Sandbox Code Playgroud)
或者,如果你必须零碎地做事,你必须做这样的事情.
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()
Run Code Online (Sandbox Code Playgroud)
这将允许您构建一系列命令.
在名称包含“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()
Run Code Online (Sandbox Code Playgroud)
'out' 和 'err' 是包含标准输出和最终错误输出的字符串对象。