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.
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"].
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.
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!
To do that, you would have to:
shell=True
argument in the subprocess.Popen
call, and;
if running under a *nix shell (bash, ash, sh, ksh, csh, tcsh, zsh etc)&
if running under the cmd.exe
of WindowsThere 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With