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')?
4 Answers 4
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 is an instance of PosixPath which has all the goodies like / and .parents etc. You need to convert it to a string if you want to append it to sys.path.
2 Comments
resolve() the Path before adding it to sys.path. That makes it absolute -- file isnt't always absolute.Support for path-like-objects on sys.path is coming (see this pull request) but not here yet.
Comments
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
1 Comment
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?
11 Comments
.parents[2] in your answeros.path is a perfectly fine library indeed! and for python <3 none of the pathlib stuff will work.
str?str: The string representation of a path is the raw filesystem path itself (in native form, e.g. with backslashes under Windows), which you can pass to any function taking a file path as a string.