Skip to content

Instantly share code, notes, and snippets.

@jterstriep
Created March 2, 2016 15:50
Show Gist options
  • Select an option

  • Save jterstriep/d109bedba77dc123f053 to your computer and use it in GitHub Desktop.

Select an option

Save jterstriep/d109bedba77dc123f053 to your computer and use it in GitHub Desktop.
Source a shell script from within a python program.
from subprocess import Popen, PIPE
from os import environ
def source(script, update=True):
"""Source a bash script from within Python
Two step process of creating a new shell with updated environmental variables and
using its env to update the scripts's environment.
http://pythonwise.blogspot.com/2010/04/sourcing-shell-script.html
"""
pipe = Popen(". %s; env" % script, stdout=PIPE, shell=True)
data = pipe.communicate()[0]
env = dict((line.split("=", 1) for line in data.splitlines()))
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