lunedì 15 ottobre 2012

Python: "source" a shell script and read variables

It comes handy to "source" a shell script and read variables from there in python, maybe to share configuration between different scripts.

Here is my* take:

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

Also available as a github gist.

* Heavily inspired from this pythonwise blog post



Nessun commento:

Posta un commento