Set pythonpath before import operations

My code is:

import scriptlib.abc import scriptlib.xyz def foo(): ... some operations 

but scriptlib is in a different directory, so I have to include this directory in the environment variable "PYTHONPATH".

In any case, I can add the scriptlib directory to the "PYTHONPATH" environment variable before executing the import statement, for example:

 import sys sys.path.append('/mypath/scriptlib') import scriptlib.abc import scriptlib.xyz def foo(): ... some operations 

If so, is this value only for this command line or is it global?

Thank you in advance

+31
python path pythonpath
Feb 27 '13 at 10:20
source share
2 answers

This will add the path to your Python process / instance (i.e. the executable executable). The path will not be changed for any other Python processes. Another working Python program will not change its path, and if you exit your program and run it again, the path will not include what you added earlier. What you do is usually 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 start loop.py connected to your STDOUT and it will continue to run in the background. Then you can run python set.py Each of them has a different set of environment variables. Note that the output from loop.py does not change, since set.py does not change the environment of loop.py

Import Note

Python imports are dynamic, like the rest of the language. Static communication does not occur. Import is an executable line, like sys.path.append...

+31
Feb 27 '13 at 10:24
source share

As also noted in the docs here .
Go to Python XX/Lib and add these lines to site.py there,

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

This modifies your sys.path so that at every boot it has that value in it.

As stated here about site.py ,

This module is automatically imported during initialization. Importing this module will add paths to a specific site to the module search path and add some built-in components.

For other possible ways to add some path to sys.path see these docs

+5
Feb 27 '13 at 10:36
source share



All Articles