Python:相对于当前正在运行的脚本添加到 sys.path 的最佳方式 [英] Python: Best way to add to sys.path relative to the current running script
问题描述
我有一个充满脚本的目录(比方说project/bin
).我还有一个位于 project/lib
的库,并希望脚本自动加载它.这是我通常在每个脚本顶部使用的:
I have a directory full of scripts (let's say project/bin
). I also have a library located in project/lib
and want the scripts to automatically load it. This is what I normally use at the top of each script:
#!/usr/bin/python
from os.path import dirname, realpath, sep, pardir
import sys
sys.path.append(dirname(realpath(__file__)) + sep + pardir + sep + "lib")
# ... now the real code
import mylib
这有点麻烦,丑陋,必须粘贴在每个文件的开头.有没有更好的方法来做到这一点?
This is kind of cumbersome, ugly, and has to be pasted at the beginning of every file. Is there a better way to do this?
我真的希望像这样顺利:
Really what I'm hoping for is something as smooth as this:
#!/usr/bin/python
import sys.path
from os.path import pardir, sep
sys.path.append_relative(pardir + sep + "lib")
import mylib
或者更好的是,当我的编辑器(或其他具有提交访问权限的人)决定将导入重新排序作为其清理过程的一部分时,它不会中断:
Or even better, something that wouldn't break when my editor (or someone else who has commit access) decides to reorder the imports as part of its clean-up process:
#!/usr/bin/python --relpath_append ../lib
import mylib
这不会直接移植到非 posix 平台,但可以保持干净.
That wouldn't port directly to non-posix platforms, but it would keep things clean.
推荐答案
如果不想编辑每个文件
- 像普通的python库一样安装你的库
或 - 将
PYTHONPATH
设置为您的lib
- Install you library like a normal python libray
or - Set
PYTHONPATH
to yourlib
或者如果您愿意为每个文件添加一行,请在顶部添加导入语句,例如
or if you are willing to add a single line to each file, add a import statement at top e.g.
import import_my_lib
将 import_my_lib.py
保留在 bin 中,import_my_lib
可以正确地将 python 路径设置为您想要的任何 lib
keep import_my_lib.py
in bin and import_my_lib
can correctly set the python path to whatever lib
you want
这篇关于Python:相对于当前正在运行的脚本添加到 sys.path 的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!