[英]Python import from own module
I have a module 'hydro' with the structure:我有一个结构为“hydro”的模块:
hydro/
__init__.py
read.py
write.py
hydro_main.py
This gets used as a submodule for several other modules, which have scripts with similar names:这被用作其他几个模块的子模块,这些模块具有类似名称的脚本:
scenarios/
__init__.py
read.py
write.py
scenarios_main.py
hydro/
__init__.py
read.py
write.py
hydro_main.py
In order to keep the script names straight, I want to specify the module name on import.为了使脚本名称保持直截了当,我想在导入时指定模块名称。 So in the header of hydro_main.py, I'd have:所以在hydro_main.py的header中,我有:
import hydro.read
and in scenarios_main.py, I'd have:在scenario_main.py中,我有:
import hydro.read as read_hydro
import scenarios.read as read_scenarios
The problem is that when I attempt to run hydro_main.py from the package root, I get the following error:问题是,当我尝试从 package 根目录运行 hydro_main.py 时,我收到以下错误:
ModuleNotFoundError: No module named 'hydro'
How can I set the package name for 'hydro' such that it will allow me to refer to the package name on import?如何为“hydro”设置 package 名称,以便在导入时引用 package 名称? I thought adding __init__.py
was supposed to initialize the package, but __package__
still comes back as None
.我认为添加__init__.py
应该初始化 package,但__package__
仍然返回为None
。
You can import just the entire module as one instance.您可以仅将整个模块作为一个实例导入。
import hydro
from hydro import read as read_hydro, hydro_main as main
hydro.hydro_main()
main() # same as above
hydro.read()
read_hydro() #same as above
It is a sub module so you have to use parentModule.subModule.*.它是一个子模块,所以你必须使用 parentModule.subModule.*。 Your first line will change to import scenarios.hydro.read as read_hydro您的第一行将更改为import scenario.hydro.read as read_hydro
print("I am in hydro_main")
print("I am in hydro read")
print("I am in hydro write")
print("I am in scenarios read")
print("I am in scenarios write")
import scenarios.hydro.read as read_hydro
import scenarios.read as read_scenarios
I am in hydro read我在水电阅读
I am in scenarios read我正在阅读的场景中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.