Skip to content

Instantly share code, notes, and snippets.

@Fifan31
Forked from mammadori/source.py
Created January 5, 2016 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fifan31/1b41568eff1f8e3940bc to your computer and use it in GitHub Desktop.
Save Fifan31/1b41568eff1f8e3940bc to your computer and use it in GitHub Desktop.
Python: "source" a shell script and read variables
from subprocess import Popen, PIPE
from os import environ
def source(script, update=True, clean=True):
"""
Source variables from a shell script
import them in the environment (if update==True)
and report only the script variables (if clean==True)
"""
global environ
if clean:
environ_back = dict(environ)
environ.clear()
pipe = Popen(". %s; env" % script, stdout=PIPE, shell=True)
data = pipe.communicate()[0]
env = dict((line.split("=", 1) for line in data.splitlines()))
if clean:
# remove unwanted minimal vars
env.pop('LINES', None)
env.pop('COLUMNS', None)
environ = dict(environ_back)
if update:
environ.update(env)
return env
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment