[英]Importing package from parallel or higher order directory in Python 3.6+
My python project is structured as follows 我的python项目的结构如下
In order to user logr.py of comUtil package from dataPreparation package one has to tweak its sys path as follows 为了从dataPreparation包中使用comUtil包的用户logr.py,必须如下调整其sys路径
import sys sys.path.append('../') import comUtil.logr as logg
Now the question is 现在的问题是
Is this an accepted practice and are there any drawbacks for such usage ? 这是公认的做法吗?这种用法有任何缺点吗?
What are other alternatives and possibly better ? 还有什么其他选择,可能更好吗?
One solution could be to set the path till dataIngestionTool
. 一种解决方案是设置直到
dataIngestionTool
的路径。 Because this is your project's root directory. 因为这是您项目的根目录。 And then import files as:
然后将文件导入为:
from dataIngestionTool.comUtil.logr import *
or 要么
from dataIngestionTool.comUtil import logr
sys.path.append('../')
permanently appends this path to the list. sys.path.append('../')
将此路径永久添加到列表中。 Now, if you are going to import a_random_module
for example in driver.py
, the package manager will also start looking for a_random_module
in the parent directory of driver.py
. driver.py
import a_random_module
,则包管理器还将开始在a_random_module
的父目录中driver.py
。 I would suggest something like this to add a certain path to sys: 我建议这样的事情为sys添加特定路径:
import sys import os def append_specific_dir_to_sys_path(): current_dir = os.getcwd() parent_dir = current_dir.split('/')[:-1] import_dir = '/'.join(parent_dir) + '/comUtil/' sys.path.append(import_dir) append_specific_dir_to_sys_path()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.