[英]Absolute and relative imports with respect to structure of a project
I'm having a hard time understanding how imports work in Python 3.x. 我很难理解Python 3.x中的导入方式。 Suppose I have a project structure like this
假设我有一个像这样的项目结构
test
../foo
....foo1.py
....foo2.py
../bar
....bar1.py
My understanding is that foo
and bar
can be treated as packages and the .py
files as modules. 我的理解是
foo
和bar
可以视为包,而.py
文件可以视为模块。
I want to import foo1
and bar1
in foo2
(which is the main script). 我想在
foo2
导入foo1
和bar1
(这是主脚本)。 How can that be done in both absolute and relative ways? 如何以绝对和相对方式做到这一点?
If I want to execute foo2
after this, is this a bad project structure (maybe foo2
should be placed elsewhere, but I do not want to place it at the root)? 如果要在此之后执行
foo2
,这是否是一个不好的项目结构(也许foo2
应该放在其他位置,但我不想将其放在根目录)?
Try this: 尝试这个:
import importlib
name = input('Enter module name:')
importlib.import_module(name)
If you want more information on importlib, check https://docs.python.org/3/library/importlib.html#module-importlib 如果您需要有关importlib的更多信息,请检查https://docs.python.org/3/library/importlib.html#module-importlib
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.