简体   繁体   中英

ModuleNotFoundError -> Imported module cannot import another module

Working directory is shaped like:

* main_script.py

/ module_to_import

    * __init__.py

    * script_1.py

    * script_2.py

In main_script.py we have

from module_to_import import script_1

script_1.call_something()

In script_1.py we have

import script_2

def call_something():
    something = script_2.get_something()
    something = something + 1
    return something

When main_script.py is run This returns a

ModuleNotFoundError: No Module named 'script_2'

I understand this could be provisionally resolved by directly importing script_2 into main_script.

Is there a way to resolve this so that script_1 can reliably import script_2 even when main_script has not imported script_2 itself?

When your package is structured as a subpackage, in script_1.py you can use either absolute import

import module_to_import.script_2 as script_2

or relative one:

from . import script_2

You can find the documentation about it here: https://docs.python.org/3/tutorial/modules.html#intra-package-references

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