Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source shell script and access exported variables from os.environ

I have a shell script where certain parameters are being set like:
k.sh:

export var="value"
export val2="value2"

Then I have a python script where i am calling the shell script and want to use these enviornment variables
ex1.py:

import subprocess
import os
subprocess.call("source k.sh",shell=True)
print os.environ["var"]

But I am getting a KeyError
How can I use these shell variables in my Python script?

like image 635
ftw Avatar asked May 14 '13 18:05

ftw


3 Answers

subprocess.call starts a shell in a new process, which calls source. There is no way to modify the environment within your process from a child process.

like image 71
chepner Avatar answered Oct 24 '22 02:10

chepner


You could source k.sh and run a Python one-liner to print the contents of os.environ as JSON. Then use json.loads to convert that output back into a dict in your main process:

import subprocess
import os
import json
PIPE = subprocess.PIPE
output = subprocess.check_output(
    ". ~/tmp/k.sh && python -c 'import os, json; print(json.dumps(dict(os.environ)))'",
    shell=True)
env = json.loads(output)
print(env["var"])

yields

value
like image 37
unutbu Avatar answered Oct 24 '22 02:10

unutbu


If you want to set the environment and then run a Python script, well, set the environment and run the Python script using runner:

runner:

#! /bin/bash
. k.sh
exec ex1.py

and that's it.

ex1.py:

#import subprocess
import os
#subprocess.call("source k.sh",shell=True)
print os.environ["var"]
like image 2
Diego Torres Milano Avatar answered Oct 24 '22 01:10

Diego Torres Milano