如何在不将路径追加到模块的情况下以不同的路径导入模块? [英] How to import module in different path without appending path to module?

查看:78
本文介绍了如何在不将路径追加到模块的情况下以不同的路径导入模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下回购结构


cli_stats/      
|__ __init__.py 
|__ README.md   
|__ docs/   
|     |__ docs
|__ cli_stats/  
|     |__  cli_stats.py
|     |__  league_season_init.pickle (generated from setup.py)
|__ pickle/ 
|     |__  __init__.py
|     |__  setup.py
|     |__  get_id/
|     |       |__ __init__.py
|     |       |__ get_id.py
|     |__ get_stats/
|     |       |__ __init__.py
|     |       |__ get_stats.py
|     |__ api_scraper/
|         |__ __init__.py
|         |__ api_scraper.py
|         |__  check_api.py
|       
|__ directory/  
|    |__ __init__.py
|    |__ directory.py
|__clean_stats/ 
     |__ __init__.py
     |__ clean_stats.py

如何将例如导入directory.py导入到clean_stats.py而不直接将directory.py的路径插入到clean_stats.py?我现在在做什么:

How can I import for example import directory.py to clean_stats.py without inserting the path to directory.py to clean_stats.py directly? What I'm doing now:

sys.path.insert(0, '../directory')
from directory import Directory

我想做什么:

from directory import Directory

是否可以利用__init__.py进行此类导入?

Is there someway to utilise the __init__.py to be able to do these kind of imports?

推荐答案

clean_stats.py中:

from ..directory import Directory

要识别Directory,而不必编写

from ..directory.directory import Directory,您需要输入 在directory/__init__.py:

from . import Directory

最后,从上一级(即,从cli_stats的父文件夹中的脚本)导入软件包时,所有相对导入都可以正常工作.

Finally, all relative imports work fine when you import your package from one upper level, that is, from a script in the parent folder of cli_stats.

如果从程序包中的其他入口点开始执行,则始终会有导入失败,除非您从启动脚本的角度修复了相对路径.问题是,如果这样做,您将只能修复一个地方,而其他地方则总是会出错.因此,使导入包可以从外部导入和使用,而不是直接从内部脚本运行.即使您编写的绝对导入路径都以包名开头,但此问题仍然存在,因为内部起点看不到外部子包.

If you start execution from some other entry point inside your package, there are always imports that will fail, unless you fix the relative path from the point of view of the starting script. Problem is, if you do that, you fix one place and others will become wrong, always. So make your import package to be imported and used from outside, not to run directly from an inside script. Even if you write absolute import paths starting with the package name everywhere, this issue persists because the inner starting point cannot see the outer subpackages.

请注意,还有其他选项,例如像您一样添加sys.path,定义PYTHONPATH或通过pippip -e将软件包安装在系统或virtualenv中.但是,所有这些选项通常用于您依赖的其他库,而不用于包的内部.

Note that there are other options like appending sys.path as you did, defining PYTHONPATH, or having packages installed in the system or in a virtualenv via pip, pip -e and so on. But all this options are usually for additional libraries you depend on, not for your package internals.

这篇关于如何在不将路径追加到模块的情况下以不同的路径导入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆