I want to open a process and run two commands in the same process. I have :
cmd1 = 'source /usr/local/../..'
cmd2 = 'ls -l'
final = Popen(cmd2, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
stdout, nothing = final.communicate()
log = open('log', 'w')
log.write(stdout)
log.close()
If I use popen two times, these two commands will be executed in different processes. But I want them to run in the same shell.
Running Multiple Commands as a Single Job We can start multiple commands as a single job through three steps: Combining the commands – We can use “;“, “&&“, or “||“ to concatenate our commands, depending on the requirement of conditional logic, for example: cmd1; cmd2 && cmd3 || cmd4.
Run Multiple Commands at Once In Linux: You can use the | operator to concatenate two commands. The first command will list the files and folders in the directory, and the second command will print the output All the files and folders are listed.
The main difference is that subprocess. run() executes a command and waits for it to finish, while with subprocess. Popen you can continue doing your stuff while the process finishes and then just repeatedly call Popen.
The commands will always be two (unix) processes, but you can start them from one call to Popen
and the same shell by using:
from subprocess import Popen, PIPE, STDOUT
cmd1 = 'echo "hello world"'
cmd2 = 'ls -l'
final = Popen("{}; {}".format(cmd1, cmd2), shell=True, stdin=PIPE,
stdout=PIPE, stderr=STDOUT, close_fds=True)
stdout, nothing = final.communicate()
log = open('log', 'w')
log.write(stdout)
log.close()
After running the program the file 'log' contains:
hello world
total 4
-rw-rw-r-- 1 anthon users 303 2012-05-15 09:44 test.py
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