每当我使用sys.path。追加,新目录将被添加。然而,一旦我关闭python,列表将恢复到以前的(默认?)值。如何将目录永久添加到PYTHONPATH?
当前回答
在linux上,您可以创建从包到PYTHONPATH目录的符号链接,而不必处理环境变量。喜欢的东西:
ln -s /your/path /usr/lib/pymodules/python2.7/
其他回答
为了给出更多的解释,Python将使用site.py脚本(通常位于sys. py中)自动构造它的搜索路径(如上所述和这里)。Prefix + lib/python<version>/site-packages以及lib/site-python)。可以获取sys.prefix的值:
python -c 'import sys; print(sys.prefix)'
The site.py script then adds a number of directories, dependent upon the platform, such as /usr/{lib,share}/python<version>/dist-packages, /usr/local/lib/python<version>/dist-packages to the search path and also searches these paths for <package>.pth config files which contain specific additional search paths. For example easy-install maintains its collection of installed packages which are added to a system specific file e.g on Ubuntu it's /usr/local/lib/python2.7/dist-packages/easy-install.pth. On a typical system there are a bunch of these .pth files around which can explain some unexpected paths in sys.path:
python -c 'import sys; print(sys.path)'
因此,可以创建一个.pth文件,并将其放在这些目录中的任何一个目录中(包括上面提到的sitedir)。这似乎是大多数包被添加到系统的方式。而不是使用PYTHONPATH。
Note: On OSX there's a special additional search path added by site.py for 'framework builds' (but seems to work for normal command line use of python): /Library/Python/<version>/site-packages (e.g. for Python2.7: /Library/Python/2.7/site-packages/) which is where 3rd party packages are supposed to be installed (see the README in that dir). So one can add a path configuration file in there containing additional search paths e.g. create a file called /Library/Python/2.7/site-packages/pip-usr-local.pth which contains /usr/local/lib/python2.7/site-packages/ and then the system python will add that search path.
A <-> B之间的最短路径是一条直线;
import sys
if not 'NEW_PATH' in sys.path:
sys.path += ['NEW_PATH']
除了操作PYTHONPATH,您还可以创建一个路径配置文件。首先找出Python在哪个目录中搜索这些信息:
python -m site --user-site
出于某种原因,这在Python 2.7中似乎不起作用。你可以使用:
python -c 'import site; site._script()' --user-site
然后在该目录中创建一个.pth文件,其中包含您想要添加的路径(如果目录不存在,则创建该目录)。
例如:
# find directory
SITEDIR=$(python -m site --user-site)
# create if it doesn't exist
mkdir -p "$SITEDIR"
# create new .pth file with our path
echo "$HOME/foo/bar" > "$SITEDIR/somelib.pth"
对我来说,当我更改.bash_profile文件时,它起作用了。只是改变.bashrc文件工作,直到我重新启动shell。
对于python 2.7,它应该是这样的:
export PYTHONPATH="$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python"
在.bash_profile文件的末尾。
为了添加awesomo的答案,你也可以在~/中添加这一行。Bash_profile或~/.profile
推荐文章
- 使用python创建一个简单的XML文件
- APT命令行界面式的yes/no输入?
- 如何打印出状态栏和百分比?
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试
- 插入一行到熊猫数据框架
- 要列出Pandas DataFrame列
- 在Django模型中存储电话号码的最佳方法是什么?
- 从导入的模块中模拟函数