python3.9
So I have a subprocess like so
m_env = os.environ.copy()
process = subprocess.Popen(
['export', 'TEST=test'],
env=m_env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True
)
result = process.wait()
new_env = process.getenv() #how to get this so the new_env has the 'TEST=test' in it.
Now the subprocess itself is modifying the env, and i wanna know how can i get this modified env from the process, the example is using export, however i run a script which may change or add other env variables, so i'd like to get the whole env.
CodePudding user response:
You can print all the environment variables in the subprocess shell, but you have to parse the data afterwards.
import os
import subprocess
def main():
m_env = os.environ.copy()
process = subprocess.Popen(
['export TEST=test && export'],
env=m_env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True
)
process.wait()
print(process.stdout.read()) # all environment variables
if __name__ == '__main__':
main()
Edit: Changed environment printing function from printenv
(which can be ambiguous when parsing) to export
. Thanks to Charles Duffy
CodePudding user response:
The solution posted by @Pavel Hamerník was the starting point. With the guidance of comment discussions from @Charles Duffy, the following solution is what works best for my implementation.
import os
import subprocess
def main():
m_env = os.environ.copy()
process = subprocess.Popen(
['/bin/bash', '-c', '. /path/script.sh && export > /tmp/env.txt'],
env=m_env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True
)
process.wait()
print(process.stdout.read()) # read the stdout from script
if __name__ == '__main__':
main()
Note: the export output is being directed to a file in /tmp/
.