Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Commands Sequentially in Python?

Tags:

I would like to execute multiple commands in a row:

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

cmd (the shell)

then

cd dir

and

ls

and read the result of the ls.

Any idea with subprocess module?

Update:

cd dir and ls are just an example. I need to run complex commands (following a particular order, without any pipelining). In fact, I would like one subprocess shell and the ability to launch many commands on it.

like image 952
MechanTOurS Avatar asked Dec 11 '08 13:12

MechanTOurS


People also ask

How do I run a sequentially command in Python?

Use """s, like this. Or, if you must do things piecemeal, you have to do something like this. That will allow you to build a sequence of commands. This failed because Popen expects a list as its first argument and just "ls" is equivalent to ["ls"].

How do you run multiple commands in Python?

Run Multiple Commands at Once In this section, you'll learn how to run multiple shell commands at once from Python. In windows: You can use the & operator to concatenate two commands. In Linux: You can use the | operator to concatenate two commands.

How do you execute a command in Python?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!


2 Answers

To do that, you would have to:

  • supply the shell=True argument in the subprocess.Popen call, and
  • separate the commands with:
    • ; if running under a *nix shell (bash, ash, sh, ksh, csh, tcsh, zsh etc)
    • & if running under the cmd.exe of Windows
like image 80
tzot Avatar answered Oct 18 '22 10:10

tzot


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.

like image 27
S.Lott Avatar answered Oct 18 '22 08:10

S.Lott