Execute Commands Sequentially in Python?

前端 未结 5 1934
猫巷女王i
猫巷女王i 2020-12-03 07:33

I would like to execute multiple commands in a row:

i.e. (just to illustrate my need):

cmd (the shell)

then

cd dir<

5条回答
  •  我在风中等你
    2020-12-03 08:11

    There is an easy way to execute a sequence of commands.

    Use the following in subprocess.Popen

    "command1; command2; command3"
    

    Or, if you're stuck with windows, you have several choices.

    • Create a temporary ".BAT" file, and provide this to subprocess.Popen

    • Create a sequence of commands with "\n" separators in a single long string.

    Use """s, like this.

    """
    command1
    command2
    command3
    """
    

    Or, if you must do things piecemeal, you have to do something like this.

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

    That will allow you to build a sequence of commands.

提交回复
热议问题