24

我想连续执行多个命令:

即(只是为了说明我的需要):

cmd(贝壳)

然后

cd dir

ls

并读取ls.

subprocess对模块有任何想法吗?

更新:

cd dir并且ls只是一个例子。我需要运行复杂的命令(按照特定的顺序,没有任何流水线)。事实上,我想要一个子进程 shell 并能够在其上启动许多命令。

4

5 回答 5

29

为此,您必须:

  • 在调用中提供shell=True参数subprocess.Popen,并且
  • 将命令分开:
    • ;如果在 *nix shell(bash、ash、sh、ksh、csh、tcsh、zsh 等)下运行
    • &如果在cmd.exeWindows下运行
于 2008-12-11T15:35:32.687 回答
23

有一种简单的方法可以执行一系列命令。

使用以下内容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()

这将允许您构建一系列命令。

于 2008-12-11T14:23:17.213 回答
5

在名称包含“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' 是包含标准输出和最终错误输出的字符串对象。

于 2008-12-11T13:59:46.997 回答
2

是的,该subprocess.Popen()函数支持cwd关键字参数,您可以使用它设置运行进程的目录。

我想第一步,shell,是不需要的,如果你只想运行ls,就不需要通过 shell 运行它。

当然,您也可以将所需目录作为参数传递给ls.

更新:可能值得注意的是,对于典型cd的 shell,它是在 shell 本身中实现的,它不是磁盘上的外部命令。这是因为它需要更改进程的当前目录,这必须在进程内完成。由于命令作为由 shell 生成的子进程运行,因此它们无法执行此操作。

于 2008-12-11T13:35:39.243 回答
-3

下面的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])
于 2015-10-03T14:18:30.167 回答