题
我想连续执行多个命令:
IE。(只是为了说明我的需要):
cmd
(贝壳)
然后
cd dir
和
ls
并读取结果 ls
.
任何想法与 subprocess
模块?
更新:
cd dir
和 ls
只是一个例子。我需要运行复杂的命令(遵循特定的顺序,没有任何管道)。事实上,我想要一个子进程 shell 并能够在其上启动许多命令。
解决方案
有一种简单的方法可以执行一系列命令。
使用以下内容 subprocess.Popen
"command1; command2; command3"
或者,如果您一直使用 Windows,您有多种选择。
创建一个临时“.BAT”文件,并将其提供给
subprocess.Popen
在单个长字符串中创建带有“ ”分隔符的命令序列。
使用“”,像这样。
"""
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()
这将允许您构建一系列命令。
其他提示
为此,您必须:
- 供应
shell=True
论据中的subprocess.Popen
打电话,并且 - 将命令分开:
;
如果在 *nix shell 下运行(bash、ash、sh、ksh、csh、tcsh、zsh 等)&
如果运行在cmd.exe
窗户的数量
查找在其名称的每个文件“酒吧”包含“富”:
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()
“出”和“ERR”是含有标准输出的字符串对象,并最终的错误输出。
是,则subprocess.Popen()
函数支持cwd
关键字参数,使用它可以将其设置在运行过程中的目录。
我想第一步,外壳,是不需要的,如果你想要的是运行ls
,没有必要通过一个shell来运行它。
当然,也可以只通过所希望的目录作为参数ls
。
更新:它可能是值得注意的是,对于典型的壳,cd
在外壳本身来实现,这不是在磁盘上的外部命令。这是因为它需要改变进程的当前目录下,必须从过程中完成。由于命令运行作为子处理,由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])
不隶属于 StackOverflow