Skip to content

Instantly share code, notes, and snippets.

@reedstrm
Last active November 16, 2015 20:41
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 reedstrm/c16f21f21d1fbb518c8f to your computer and use it in GitHub Desktop.
Save reedstrm/c16f21f21d1fbb518c8f to your computer and use it in GitHub Desktop.
Using session_exec to initialize plpythonu virtualenv inside postgresql

It is possible using the session_exec extension to postgresql to run a single function at session creation time

CREATE FUNCTION workon(venv text) RETURNS void
    LANGUAGE plpythonu
    AS $_$
    import os
    import sys

    if sys.platform in ('win32', 'win64', 'cygwin'):
        activate_this = os.path.join(venv, 'Scripts', 'activate_this.py')
    else:
        if not os.environ.has_key('PATH'):
            import subprocess
            p=subprocess.Popen('echo -n $PATH', stdout=subprocess.PIPE, shell=True)
            (mypath,err) = p.communicate()
            os.environ['PATH'] = mypath

        activate_this = os.path.join(venv, 'bin', 'activate_this.py')

    exec(open(activate_this).read(), dict(__file__=activate_this))
$_$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment