Question

In one of my python scripts I am using import statement at the top of the file as below.

import phx_commonlib.configuration.systemConfig as systemConfig

It will look for PYTHONPATH environment variable which is set in ~/.bashrc file, and it is importing the file fine when I run from bash shell on linux box. Later I connected to my linux box using putty and now my script failed from putty because ~/.bashrc file won't be sourced. So I exported PYTHONPATH variable inside the script as below.

def exportPythonPath():
    pwd = os.getcwd()

    pythonpath = ""

    scanPath_index = pwd.find('/phx_test/scan')
    if scanPath_index != -1:
        pythonpath = pwd[0:scanPath_index]
        pythonpath = pythonpath + ":/projects/phx/tools:/projects/phx/tools/pylib"
        os.environ["PYTHONPATH"] = pythonpath
        print os.environ["PYTHONPATH"]

and I am importing "import phx_commonlib.configuration.systemConfig as systemConfig" after setting the PYTHONPATH inside a function (if I keep import at the top it will fail because it won't find PYTHONPATH). print statement at the end of the function wrote above is printing the correct PYTHONPATH environment variable. But still import statement is not working. It is throwing error saying that "ImportError: No module named phx_commonlib.configuration.systemConfig".

If I set PYTHONPATH directly from putty (instead of setting from script) and if I run the python script, it is importing the module properly. Can any one please let me know the problem in the script or how to do the import.

Was it helpful?

Solution

Instead of setting PYTHONPATH in os.environ, you need to to modify sys.path, like:

import sys
sys.path.append(pythonpath)

And then go on with your imports.

The reason setting PYTHONPATH in os.environ does not work is that sys.path is what the interpreter refers to at the point of executing an import directive.

If you set a PYTHONPATH environment variable and then start the interpreter, it would see it, add it to sys.path, and carry on.

If you start the interpreter with no PYTHONPATH env-var set, sys.path would not be updated at startup, and the new value in os.environ['PYTHONPATH'], which is set after the interpreter-startup, will be left unused.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top