set pythonpath before import statements

PythonPathPythonpath

Python Problem Overview


My code is:

import scriptlib.abc
import scriptlib.xyz

def foo():
  ... some operations

but the scriptlib is in some other directory, so I will have to include that directory in environment variable "PYTHONPATH".

Is there anyway in which I can first add the scriptlib directory in environment variable "PYTHONPATH" before import statement getting executed like :

import sys
sys.path.append('/mypath/scriptlib')
import scriptlib.abc
import scriptlib.xyz

def foo():
  ... some operations

If so, is the value only for that command prompt or is it global ?

Thanks in advance

Python Solutions


Solution 1 - Python

This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.

set.py:

import sys
sys.path.append("/tmp/TEST")

loop.py

import sys
import time
while True:
  print sys.path
  time.sleep(1)

run: python loop.py &

This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py. Each has a different set of environment variables. Observe that the output from loop.py does not change because set.py does not change loop.py's environment.

A note on importing

Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append....

Solution 2 - Python

As also noted in the docs here.

Go to Python X.Y/Lib (Windows) or /usr/lib/pythonX.Y (Linux) and add these lines to the site.py there,

import sys
sys.path.append("yourpathstring")

This changes your sys.path so that on every load, it will have that value in it..

As stated here about site.py,

>This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.

For other possible methods of adding some path to sys.path see these docs

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDKGView Question on Stackoverflow
Solution 1 - PythonJoeView Answer on Stackoverflow
Solution 2 - PythonpradyunsgView Answer on Stackoverflow