Adding a directory to sys.path with pathlib

Question:

I’m trying to add a directory to PATH with 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')?

Asked By: kharandziuk

||

Answers:

From the docs:

A program is free to modify this list for its own purposes. Only strings should be added to sys.path; all other data types are ignored during import.

Add the path as a string to sys.path:

PROJECT_DIR = Path(__file__).parents[2]
sys.path.append(
    str(PROJECT_DIR / 'apps')
)
Answered By: hiro protagonist
project_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)),"..","..")
sys.path.append(os.path.join(project_dir,"apps"))
#or maybe you need it at the start of the path
sys.path.insert(0,os.path.join(project_dir,"apps"))

why are you using this weird pathlib library instead of pythons perfectly good path utils?

Answered By: Joran Beasley

You could also use os.fspath. It return the file system representation of the path.

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

Documentation:
https://docs.python.org/3/library/os.html#os.fspath

Answered By: Jack Klimov

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

Answered By: Tom
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.