在无法修改PYTHONPATH时,如何在Python中导入其他模块?
我正在用Python编写我的第一个项目,但对如何处理导入有些困惑。我在大学的电脑上工作,无法修改PYTHONPATH这个变量。而且我还在不同的电脑和操作系统上进行这个项目,所以项目的路径并不总是相同。
我有很多不同的模块,它们分布在不同的文件夹里,彼此之间需要导入。目前,我是通过使用file_path = os.path.abspath(__file__)
来获取一个模块的路径,然后再回溯到上级目录,最后把包含所需模块的文件夹路径添加到PYTHONPATH中,使用sys.path.append(symantic_root)
。
这种方法虽然能用,但看起来很乱,而且每个模块开头都有很多重复的代码,比如:
import os
import sys
# Get the path to the directory above the directory this file is in, for any system
file_path = os.path.abspath(__file__)
root_path = os.path.dirname(os.path.dirname(file_path))
# Get the paths to the directories the required modules are in
symantic_root = os.path.join(root_path, "semantic_analysis")
parser_root = os.path.join(root_path, "parser")
# Add the directories to the path variable
sys.path.append(symantic_root)
sys.path.append(parser_root)
import semantic_analyser
import jaml
如果有更好的项目结构建议,我会非常感激。
3 个回答
你没有提到你使用的是什么操作系统。很多回答都是基于Linux(或类似Unix的系统)环境。如果你是在Windows上,可能需要其他人来补充。
从你的例子来看,不太清楚你为什么要经历这么多复杂的步骤。首先,你为什么不能修改PYTHONPATH
呢?这其实只是一个shell环境变量。如果你能登录并运行Python,那说明你有权限设置自己的环境变量。
不过我甚至不确定这是否真的必要。如果你直接把所有自定义模块安装到你自己的库目录里,并按照vinilios的建议安装.pth
文件,你可以这样做:
import site
import os
site.addsitedir(os.path.expanduser('~/lib/python'))
你可能还想看看virtualenv这个包,它可以让你创建自己的Python环境,在里面安装你自己的包。当你需要安装系统Python中没有的模块时,这个工具非常方便。
首先,你应该看看关于Python路径的一些资料,以下这些文档会很有帮助:
- http://docs.python.org/tutorial/modules.html#the-module-search-path
- http://www.doughellmann.com/PyMOTW/site/index.html
要解决你的问题,你可以使用一个
然后在你的主脚本中,你可以这样做:
import site
site.addsitedir(".")
这样做会自动把那些目录添加到PYTHONPATH
里。
首先,创建一个简单的 main.py
脚本,这个脚本是你应用程序的入口点。比如说:
if __name__ == '__main__':
import sys
from package import app
sys.exit(app.run())
接下来,创建一个顶层的包,把你所有的模块放在一起,并确保这个包和 main.py
在同一个文件夹里。这样,你就可以去掉所有处理路径的代码,直接使用完整的导入语句,比如 from package.module import function
,在你应用程序的任何模块中都可以这样使用。