Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding directory to sys.path /PYTHONPATH

People also ask

Is Pythonpath same as SYS path?

PYTHONPATH is related to sys. path very closely. PYTHONPATH is an environment variable that you set before running the Python interpreter. PYTHONPATH , if it exists, should contain directories that should be searched for modules when using import .

How do I permanently add a sys path in Python?

On each line of the file you put one directory name, so you can put a line in there with /path/to/the/ and it will add that directory to the path. You could also use the PYTHONPATH environment variable, which is like the system PATH variable but contains directories that will be added to sys.

How does Python set SYS path?

By default, sys. path is constructed as a concatenation of (1) the current working directory, (2) content of PYTHONPATH environment variable, and (3) a set of default paths supplied by the installed Python interpreter. The error can occur either because the module is indeed missing on your system, or because the sys.


This is working as documented. Any paths specified in PYTHONPATH are documented as normally coming after the working directory but before the standard interpreter-supplied paths. sys.path.append() appends to the existing path. See here and here. If you want a particular directory to come first, simply insert it at the head of sys.path:

import sys
sys.path.insert(0,'/path/to/mod_directory')

That said, there are usually better ways to manage imports than either using PYTHONPATH or manipulating sys.path directly. See, for example, the answers to this question.


You could use:

import os
path = 'the path you want'
os.environ['PATH'] += ':'+path

As to me, i need to caffe to my python path. I can add it's path to the file /home/xy/.bashrc by add

export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH.

to my /home/xy/.bashrc file.

But when I use pycharm, the path is still not in.

So I can add path to PYTHONPATH variable, by run -> edit Configuration.

enter image description here


Temporarily changing dirs works well for importing:

cwd = os.getcwd()
os.chdir(<module_path>)
import <module>
os.chdir(cwd)