Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set pythonpath before import statements

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

like image 801
DKG Avatar asked Feb 27 '13 10:02

DKG


People also ask

When should I set Pythonpath?

The only reason to set PYTHONPATH is to maintain directories of custom Python libraries that you do not want to install in the global default location (i.e., the site-packages directory).

How do I permanently set Pythonpath in Linux?

Type open . bash_profile. In the text file that pops up, add this line at the end: export PYTHONPATH=$PYTHONPATH:foo/bar. Save the file, restart the Terminal, and you're done.


1 Answers

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....

like image 162
Joe Avatar answered Oct 16 '22 03:10

Joe