简体   繁体   中英

Python import from own module

I have a module 'hydro' with the structure:

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:

import hydro.read

and in scenarios_main.py, I'd have:

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:

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? I thought adding __init__.py was supposed to initialize the package, but __package__ still comes back as 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.*. Your first line will change to import scenarios.hydro.read as read_hydro

scenarios/hydro/hydro_main.py

print("I am in hydro_main")

scenarios/hydro/read.py

print("I am in hydro read")

scenarios/hydro/write.py

print("I am in hydro write")

scenarios/read.py

print("I am in scenarios read")

scenarios/write.py

print("I am in scenarios write")

scenarios/scenarios_main.py

import scenarios.hydro.read as read_hydro
import scenarios.read as read_scenarios

I am in hydro read

I am in scenarios read

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM