san*_*ica 12 python import package python-import
I have the following directory structure:
py_test
??? __init__.py
??? dir1
? ??? __init__.py
? ??? script1.py
??? dir2
??? __init__.py
??? script2.py
Run Code Online (Sandbox Code Playgroud)
In script2 I want to "import ..\script1".
What I tried in script2:
Does not work
from ..dir1 import script1
ImportError: attempted relative import with no known parent package`
Run Code Online (Sandbox Code Playgroud)Works
import sys, os
path2add = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'dir1')))
if (not (path2add in sys.path)) :
sys.path.append(path2add)
Run Code Online (Sandbox Code Playgroud)If I want to go with option 1, what is the simplest (i.e., with the least files) file/dir structure that makes it work?
I am aware of this, but I wonder if creating that directory structure can be avoided, and still use type-1 import.
I am currently using this workaround, which uses type-2 import.
Related:
正如评论中提到的,如果 目录是您的入口点,则尝试将模块导入目录将不起作用script2.py。
如果模块
__name__不包含任何包信息(例如,将其设置为__main__),则将解析相对导入,就像该模块是顶级模块一样,无论该模块实际位于文件系统上的位置。
模块的__name__设置为__main__如果它是入口点,或者是您通过类似python script2.py.
任何这样运行的 python 模块都不再具有从更高目录导入文件所需的信息。
因此你有两个选择:
sys.path.append这将按照您想要的方式工作,但相当麻烦。
假设您的包有多个需要运行的脚本,您可以创建一个新文件来导入这两个脚本script1,script2然后根据命令行参数调用您想要的功能。然后,您将能够保留当前的目录结构,并使相对导入正常工作,而无需对sys.path.
| 归档时间: |
|
| 查看次数: |
6292 次 |
| 最近记录: |