在Python中顺序执行命令?

问题描述 投票:0回答:6

我想连续执行多个命令:

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

cmd
(外壳)

然后

cd dir

ls

并读取

ls
的结果。

subprocess
模块有什么想法吗?

更新:

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

python windows subprocess
6个回答
33
投票

要做到这一点,你必须:

  • shell=True
    调用中提供
    subprocess.Popen
    参数,并且
  • 用以下命令分隔命令:
    • ;
      如果在 *nix shell 下运行(bash、ash、sh、ksh、csh、tcsh、zsh 等)
    • &
      如果在 Windows
      cmd.exe
      下运行

25
投票

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

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()

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


6
投票

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


2
投票

是的,

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

我想第一步,shell,是不需要的,如果你只想运行

ls
,就没有必要通过shell来运行它。

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

ls

更新:可能值得注意的是,对于典型的 shell,

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


0
投票

为了更简单,只需在单个列表/元组中键入所有命令即可。然后只需迭代列表/元组并将其作为参数传递给 os 模块的 system() 函数。

from os import system

cmds = ['cmd1', 'cmd2']

for cmd in cmds:
    system(cmd)

-4
投票

下面的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])
© www.soinside.com 2019 - 2024. All rights reserved.