[英]Adding a directory to sys.path with pathlib
I'm trying to add a directory to PATH wit code like this:我正在尝试将目录添加到 PATH 机智代码,如下所示:
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:如果我确实打印
sys.path
我会看到如下内容:
[..., PosixPath('/opt/project/apps')]
How should I fix this code?我应该如何修复此代码? Is it normal to write
str(PROJECT_DIR / 'apps')
?写
str(PROJECT_DIR / 'apps')
吗?
you need to append the path as a string to sys.path
:您需要将路径作为字符串附加到
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
. PROJECT_DIR
是PosixPath
实例,它具有/
和parents
等所有优点,但如果您想在需要使用字符串的地方使用,则需要将其转换为常规字符串 - 如sys.path
。
对sys.path
上类似路径的对象的支持即将到来(请参阅此拉取请求),但还没有在这里。
You could also use os.fspath
.您也可以使用
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文档: https : //docs.python.org/3/library/os.html#os.fspath
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?为什么你使用这个奇怪的 pathlib 库而不是 python 完美的路径工具?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.