Skip to content

Instantly share code, notes, and snippets.

@sinewalker
Forked from vlasovskikh/envutils.py
Created June 17, 2021 20:58
Show Gist options
  • Save sinewalker/a15705b19e9466d22e380777d09e9fd5 to your computer and use it in GitHub Desktop.
Save sinewalker/a15705b19e9466d22e380777d09e9fd5 to your computer and use it in GitHub Desktop.
Source Bash file using a Python function
import os
from subprocess import Popen, PIPE
import pickle
PYTHON_DUMP_ENVIRON = """\
import sys
import os
import pickle
data = pickle.dumps(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
@sinewalker
Copy link
Author

Note original author's caveat:

Note that path must not contain ' characters for the function to work properly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment