我知道我可以像这样向 Python 添加导入路径:
import sys
sys.path.append("/path/to/directory/")
但是,当我重新启动 Python 时,它就消失了。如果我不得不一直这样做,我会觉得这很烦人,我想一劳永逸地做这件事并完成它。
又怎样?我在哪里可以找到那个文件?还是我需要编辑其他东西?我正在使用最新版本的 Ubuntu。
来自man python
~/.pythonrc.py
User-specific initialization file loaded by the user module; not used by default or by most applications.
ENVIRONMENT VARIABLES
PYTHONPATH
Augments the default search path for module files. The format is the same as the shell's $PATH: one or more directory pathnames
separated by colons. Non-existent directories are silently ignored. The default search path is installation dependent, but gen-
erally begins with ${prefix}/lib/python<version> (see PYTHONHOME above). The default search path is always appended to $PYTHON-
PATH. If a script argument is given, the directory containing the script is inserted in the path in front of $PYTHONPATH. The
search path can be manipulated from within a Python program as the variable sys.path .
您也可以使用路径文件。
如果您想将名为 mymodule 的模块添加到导入路径,请将文件 mymodule.pth 添加到 3rd 方模块的标准目录,通常称为 dist-packages 或 site-packages。在 Ubuntu 上,你可能会在某个地方找到它
/usr/local/lib/python2.7/dist-packages
文件 mymodule.pth 应该包含一行,即要添加到 python 导入路径的目录
<mymodule.pth>
/path/to/directory/containing/mymodule
目录中的任何 python 模块或包现在都可以从解释器中导入。
您可以设置一个名为PYTHONPATH
包含您的目录的环境变量。
在文档中阅读有关它的更多信息
从外壳执行以下操作:
echo -e "\nexport PYTHONPATH=\$PYTHONPATH:/path/to/directory" >> ~/.bashrc
并重新启动它