Adding Directory to Sys.Path /Pythonpath

adding directory to sys.path /PYTHONPATH

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.

Permanently add a directory to PYTHONPATH?

You need to add your new directory to the environment variable PYTHONPATH, separated by a colon from previous contents thereof. In any form of Unix, you can do that in a startup script appropriate to whatever shell you're using (.profile or whatever, depending on your favorite shell) with a command which, again, depends on the shell in question; in Windows, you can do it through the system GUI for the purpose.

superuser.com may be a better place to ask further, i.e. for more details if you need specifics about how to enrich an environment variable in your chosen platform and shell, since it's not really a programming question per se.

Permanently adding a file path to sys.path in Python

There are a few ways. One of the simplest is to create a my-paths.pth file (as described here). This is just a file with the extension .pth that you put into your system site-packages directory. 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.path. See the documentation.

Note that no matter what you do, sys.path contains directories not files. You can't "add a file to sys.path". You always add its directory and then you can import the file.

How to add a directory to System path variable in Python

sys.path is not the same as the PATH variable specifying where to search for binaries:

sys.path

A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.

You want to set the PATH variable in os.environ instead.

app_path = os.path.join(root_path, 'other', 'dir', 'to', 'app')
os.environ["PATH"] += os.pathsep + os.path.join(os.getcwd(), 'node')

Add a directory to Python sys.path so that it's included each time I use Python

Simply add this path to your PYTHONPATH environment variable. To do this, go to Control Panel / System / Advanced / Environment variable, and in the "User variables" sections, check if you already have PYTHONPATH. If yes, select it and click "Edit", if not, click "New" to add it.

Paths in PYTHONPATH should be separated with ";".

Add folder to PYTHONPATH programmatically

If you only want to change it for the execution of the current script, you can do it simply by assigning (or changing an existing) value in the os.environ mapping. The code below is complicated a bit by the fact that I made it work even if os.environ[PYTHONPATH] isn't initially set to anything (as is the case on my own system).

import os
from pathlib import Path

PYTHONPATH = 'PYTHONPATH'

try:
pythonpath = os.environ[PYTHONPATH]
except KeyError:
pythonpath = ''

print('BEFORE:', pythonpath)

folder = Path(__file__).resolve().parent.joinpath('code')
print(f'{folder=}')

pathlist = [str(folder)]
if pythonpath:
pathlist.extend(pythonpath.split(os.pathsep))
print(f'{pathlist=}')

os.environ[PYTHONPATH] = os.pathsep.join(pathlist)
print('AFTER:', os.environ[PYTHONPATH])

Do I need to add my project directory to the system path in every script to import a function from another directory?

First of all, let me describe you the differences between a Python module & a Python package so that both of us are on the same page. ✌


A module is a single .py file (or files) that are imported under one import and used. ✔

import aModuleName
# Here 'aModuleName' is just a regular .py file.

Whereas, a package is a collection of modules in directories that give a package hierarchy. A package contains a distinct __init__.py file. ✔

from aPackageName import aModuleName
# Here 'aPackageName` is a folder with a `__init__.py` file
# and 'aModuleName', which is just a regular .py file.


Therefore, when we have a project directory named proj-dir of the following structure ⤵

proj-dir
--|--__init__.py
--package1
--|--__init__.py
--|--module1.py
--package2
--|--__init__.py
--|--module2.py

Notice that I've also added an empty __init__.py into the proj-dir itself which makes it a package too.

Now, if you want to import any python object from module2 of package2 into module1 of package1, then the import statement in the file module1.py would be

from package2.module2 import object2
# if you were to import the entire module2 then,
from package2 import module2

I hope this simple explanation clarifies your doubts on Python imports' mechanism and solves the problem. If not then do comment here. /h3>

Python: Best way to add to sys.path relative to the current running script

If you don't want to edit each file

  • Install you library like a normal python libray

    or
  • Set PYTHONPATH to your lib

or if you are willing to add a single line to each file, add a import statement at top e.g.

import import_my_lib

keep import_my_lib.py in bin and import_my_lib can correctly set the python path to whatever lib you want

Adding a directory to sys.path with pathlib

you need to append the path as a string to sys.path:

PROJECT_DIR = Path(__file__).parents[2]
sys.path.append(
str(PROJECT_DIR / 'apps')
)

PROJECT_DIR is instance of PosixPath which has all the goodies like / and parents etc. but you need to convert it to a regular string if you want to use is somewhere a string is expected - like sys.path.

Python: Adding Directory One Level Up to System Path

You could try to add the following statement at the beginning of the file:

 import os,sys 
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

It adds the path of the module that needs to be imported to the system path.

Sample Image



Related Topics



Leave a reply



Submit