我编写我的第一个项目在Python中,我不确定如何处理导入。我正在学校的电脑上工作,无法修改PYTHONPATH变量。我也在从各种计算机/操作系统开始研究这个项目(所以项目的路径并不总是相同的)。PYTHONPATH无法修改时导入Python中的其他模块的最佳方法?
我在不同的文件夹中有许多不同的模块,它们都可以导入彼此。目前,我使用file_path = os.path.abspath(__file__)
从另一个模块获取一个模块的路径,然后通过目录回溯,然后在文件夹中添加所需的模块。然后将其添加到sys.path.append(symantic_root)
的PYTHONPATH中。
该系统的工作原理,但它结束了看起来很凌乱,有很多重复的代码在每个模块开始,例如:
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
上更好的方式来构建一个项目中的任何意见如这将非常感激。
感谢您的回复。当你说“提供接入点”时,我只是徘徊你的意思。这是否与__init__.py文件有关? –
@Alty。在你的问题中,你没有说清楚你的模块目前在什么程度上可以重新构建文件夹,我不确定你使用的是什么操作系统 - 所以“访问点”只是一个普通的目录,或者是一个符号链接等。关键是要找到一种方法,将所有模块组合在一个包中 - 然后事情变得更加简单(希望我不只是在这里说明明显)。 – ekhumoro