36

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')?

3

4 Answers 4

51

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You may want to resolve() the Path before adding it to sys.path. That makes it absolute -- file isnt't always absolute.
@florisla as this is done at runtime there is no need for that (as long as you do not move the modules before they are imported).
9

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

Comments

0

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

-12
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

may be a matter of taste - pathlib is pretty nice!
This does not answer the question.
I guess you miss this part .parents[2] in your answer
@Joran Beasley: by all means leave the answer! os.path is a perfectly fine library indeed! and for python <3 none of the pathlib stuff will work.
python love! (and: pathlib is builtin in python >3 and evidently backported to python 2.* [as mentioned by kharandziuk]).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.