在Python中按顺序执行命令

Mec*_*urS 20 python windows subprocess

我想连续执行多个命令:

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

cmd(外壳)

然后

cd dir

LS

并阅读ls的结果.

有什么想法与子进程模块?

更新:

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

tzo*_*zot 26

要做到这一点,你必须:

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

  • 或者对于 Windows,可以使用 && 以便出错的命令将阻止执行其后的命令。 (2认同)

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)

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

  • `subprocess.Popen("ls")`有效.但是,`subprocess.Popen("ls; ls")`对我来说失败了.错误:`Traceback(最近一次调用最后一次):文件"<stdin>",第1行,在<module>文件"/usr/lib64/python2.6/subprocess.py",第639行,在__init__ errread,errwrite)文件"/usr/lib64/python2.6/subprocess.py",第1228行,在_execute_child中引发child_exception OSError:[Errno 2]没有这样的文件或目录` (2认同)
  • 使用 `s = """my script with line break"""` 并使用 `subprocess.run([s], shell=True)` 运行它对我来说效果很好。 (2认同)

Oli*_*Oli 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()
Run Code Online (Sandbox Code Playgroud)

'out' 和 'err' 是包含标准输出和最终错误输出的字符串对象。