In a python3 script I need to call other commands in a particular environment (python2 among other stuff). For this I need to source a dotshrc
file in a particular directory, and then stay in that directory to run other commands.
It looks like this:
proc = subprocess.Popen("source dotshrc", shell=True, cwd="/my/dir")
# do some stuff
if foo:
proc.*run*(cmd = "myCmd1")
# do some stuff
proc.*run*(cmd = "myCmd2")
I saw multiple threads talking about running multiple commands on python sub-processes.
This one, who run all commands in a row, so I can not do my own stuff between commands runs.
This other one who looks promising, but I can't achieve to make it works. Here is a little test I wrote:
#!/usr/bin/env python3
from subprocess import Popen, PIPE
import os
my_env = os.environ.copy()
my_env["PATH"] = "/foo/:" + my_env["PATH"]
proc = Popen("echo $PATH", env=my_env, shell=True, stdin=PIPE, stdout=PIPE)
if proc.poll() is not None:
print("Exited 1")
exit()
print(repr(proc.stdout.readline()))
if proc.poll() is not None:
print("Exited 2")
exit()
print(proc)
if proc.poll() is not None:
print("Exited 3")
exit()
proc.stdin.write(b'echo')
if proc.poll() is not None:
print("Exited 4")
exit()
print(repr(proc.stdout.readline()))
if proc.poll() is not None:
print("Exited 5")
exit()
proc.stdin.write(b'ls')
if proc.poll() is not None:
print("Exited 6")
exit()
print(repr(proc.stdout.readline()))
if proc.poll() is not None:
print("Exited 7")
exit()
Most of the time it exit at Exit 2
or Exit 3