How to run multiple shell commands in one process?
Synthetic example: I want to create a directory and in it a subdirectory.

If I do this:

subprocess.call('mkdir dir', shell=True) subprocess.call('cd dir', shell=True) subprocess.call('mkdir subdir', shell=True) 

Then each command will be executed in its own subprocess, and instead of dir / subdir I will get dir and subdir on the same level.

Option

 command = 'mkdir dir && cd dir && mkdir dir2' subprocess.call(command, shell=True) 

It doesn’t look very good, and it won’t work if I want to get returncode or stdout of each command.

Ps os.chdir () is not the same, the question is, How to run several shell commands in one process?

  • And what does not suit - cmd1; cmd2 ...? - 0xdb
  • How do you know where the output of one command ends and where the output of the other command begins? If the process is one, then what kind of returncode can we talk about. If mkdir is not built into the shell, then without creating an additional process (if you don’t use mkdir -p dir/subdir and run without a shell) you can’t do. - jfs

2 answers 2

Your question already contains code that runs several shell commands inside one shell:

 rc = subprocess.call("a && b && c", shell=True) 

For the readability of large commands, you can use triple quotes with multi-line commands to use """...""" .

If you don’t want to use && , depending on your task, you can add an analogue of set -e -o pipefail to the beginning (along with executable='/bin/bash' ).

To "get the returncode or stdout of each command." , can you display the status of each command by inserting an analogue of echo $? after each command, and use pexpect so that the output after the prompt appears when the individual command has ended is easy to pull out. See Multiple inputs and python subprocess communicate .

Obviously, if you run commands that are not built into the shell, you cannot do with one process (each external command starts at least one new OS process).

Also, in order to output the output correctly, you should set the value of $PS1 so that it cannot meet in the output of your commands. For example, if you share the output by '> ' , then it may break if any of the commands prints '> ' . See how the pexpect.pxssh.set_unique_prompt() and .prompt() methods are implemented .

    Use subprocess.Popen . In it, the process is configured and runs separately from the python program flow.

    • one
      Add sample code. For this is not the answer. - Pavel Durmanov
    • The answer is that there should always be a code? I said that it is necessary for parallel work of commands, I will not write code for the author - Andrio Skur