Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run multiple commands in one process using Popen?

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.

like image 433
nsh Avatar asked Mar 10 '12 19:03

nsh


People also ask

How do you run multiple commands in one?

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.

How do I run multiple commands in Python shell?

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.

What is the difference between subprocess run and Popen?

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.


Video Answer


1 Answers

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
like image 199
Anthon Avatar answered Sep 29 '22 13:09

Anthon