Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a directory to sys.path with pathlib

Tags:

python

pathlib

I'm trying to add a directory to PATH wit code like this:

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

It doesn't work. If I do print sys.path I see something like this:

[..., PosixPath('/opt/project/apps')]

How should I fix this code? Is it normal to write str(PROJECT_DIR / 'apps')?

like image 706
kharandziuk Avatar asked Sep 21 '15 17:09

kharandziuk


People also ask

What does Pathlib path () do?

The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.

How do I add path to SYS path?

append(mod_directory) to append the path and then open the python interpreter, the directory mod_directory gets added to the end of the list sys. path. If I export the PYTHONPATH variable before opening the python interpreter, the directory gets added to the start of the list.

How can we create a directory with the Pathlib module?

Create Directory in Python Using the Path. mkdir() Method of the pathlib Module. The Path. mkdir() method, in Python 3.5 and above, takes the path as input and creates any missing directories of the path, including the parent directory if the parents flag is True .

What does import Pathlib do in Python?

The Pathlib module in Python deals with path related tasks, such as constructing new paths from names of files and from other paths, checking for various properties of paths and creating files and folders at specific paths.


2 Answers

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.

like image 122
hiro protagonist Avatar answered Oct 09 '22 15:10

hiro protagonist


Support for path-like-objects on sys.path is coming (see this pull request) but not here yet.

like image 20
Tom Avatar answered Oct 09 '22 15:10

Tom