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')
?
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')
)
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?
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
Support for path-like-objects on sys.path
is coming (see this pull request) but not here yet.
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')
?
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')
)
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?
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
Support for path-like-objects on sys.path
is coming (see this pull request) but not here yet.