-
-
Save koffie/00685aceed6ca5caefb1d07abbe9f41f to your computer and use it in GitHub Desktop.
Source Bash file using a Python function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from subprocess import Popen, PIPE | |
import pickle | |
PYTHON_DUMP_ENVIRON = """\ | |
import sys | |
import os | |
import pickle | |
data = pickle.dumps(dict(os.environ)) | |
stdout = os.fdopen(sys.stdout.fileno(), "wb") | |
stdout.write(data) | |
""" | |
def source_bash_file(path): | |
bash_cmds = [ | |
"source '%s'" % path, | |
"python -c '%s'" % PYTHON_DUMP_ENVIRON, | |
] | |
p = Popen(['bash', '-c', '&&'.join(bash_cmds)], stdout=PIPE) | |
stdout, _ = p.communicate() | |
if stdout: | |
environ = pickle.loads(stdout) | |
for k, v in environ.items(): | |
os.environ[k] = v |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment