Python: how to run multiple commands in the same 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.

+3


source to share


1 answer


Commands will always be two (unix) processes, but you can start them from one call to Popen

and with the same shell 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 starting the program, the 'log' file contains:

hello world
total 4
-rw-rw-r-- 1 anthon users 303 2012-05-15 09:44 test.py

      

+5


source







All Articles