Importing Python file from PostgreSQL stored procedure
Question: It is possible to have Python code in a PostgreSQL stored procedure. For
example:

    
    
    CREATE FUNCTION someProc()
    RETURNS void AS $$
        # Some Python3 code...
    $$ LANGUAGE plpython3u;
    

But how can I include a python file from this code?

The current directory of Python running in PostgreSQL is this:

    
    
    >>> os.getcwd()
    ... /var/lib/postgresql/9.3/main
    

I tryied the following, which worked:

    
    
    CREATE FUNCTION someProc()
    RETURNS void AS $$
        import sys
        sys.path.append("/dir/to/file")
        from python_file import pythonFunction
        # More Python code
    $$ LANGUAGE plpython3u;
    

This doesn't seem very good for many obvious reasons. Is there a better way to
import a python file, or just calling a python function from a python file?

**Edit:** There isn't any specific PostgreSQL method to import a file. But the
best way is in the correct answer bellow, which resembles my original solution
but it is better.


Answer: This is no different to dynamically loading Python code from a file in
standalone Python:

  * [How to import a module given the full path?](http://stackoverflow.com/q/67631/398670)

PL/Python3 (untrusted) is just the cpython interpreter running embedded in a
PostgreSQL backend process as the same operating system user PostgreSQL its
self runs as. With a very few differences - like thread safety - it's just
Python.

