我想连续执行多个命令:
即(只是为了说明我的需要):
cmd
(贝壳)
然后
cd dir
和
ls
并读取ls
.
subprocess
对模块有任何想法吗?
更新:
cd dir
并且ls
只是一个例子。我需要运行复杂的命令(按照特定的顺序,没有任何流水线)。事实上,我想要一个子进程 shell 并能够在其上启动许多命令。
我想连续执行多个命令:
即(只是为了说明我的需要):
cmd
(贝壳)
然后
cd dir
和
ls
并读取ls
.
subprocess
对模块有任何想法吗?
更新:
cd dir
并且ls
只是一个例子。我需要运行复杂的命令(按照特定的顺序,没有任何流水线)。事实上,我想要一个子进程 shell 并能够在其上启动许多命令。
为此,您必须:
shell=True
参数subprocess.Popen
,并且;
如果在 *nix shell(bash、ash、sh、ksh、csh、tcsh、zsh 等)下运行&
如果在cmd.exe
Windows下运行有一种简单的方法可以执行一系列命令。
使用以下内容subprocess.Popen
"command1; command2; command3"
或者,如果您被 Windows 困住,您有多种选择。
创建一个临时的“.BAT”文件,并将其提供给subprocess.Popen
在单个长字符串中创建带有“\n”分隔符的命令序列。
像这样使用“””。
"""
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()
这将允许您构建一系列命令。
在名称包含“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' 是包含标准输出和最终错误输出的字符串对象。
是的,该subprocess.Popen()
函数支持cwd
关键字参数,您可以使用它设置运行进程的目录。
我想第一步,shell,是不需要的,如果你只想运行ls
,就不需要通过 shell 运行它。
当然,您也可以将所需目录作为参数传递给ls
.
更新:可能值得注意的是,对于典型cd
的 shell,它是在 shell 本身中实现的,它不是磁盘上的外部命令。这是因为它需要更改进程的当前目录,这必须在进程内完成。由于命令作为由 shell 生成的子进程运行,因此它们无法执行此操作。
下面的python脚本有3个你刚刚执行的函数:
import sys
import subprocess
def cd(self,line):
proc1 = subprocess.Popen(['cd'],stdin=subprocess.PIPE)
proc1.communicate()
def ls(self,line):
proc2 = subprocess.Popen(['ls','-l'],stdin=subprocess.PIPE)
proc2.communicate()
def dir(silf,line):
proc3 = subprocess.Popen(['cd',args],stdin=subprocess.PIPE)
proc3.communicate(sys.argv[1])