Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModuleNotFoundError: No module named '__main__.xxxx'; '__main__' is not a package

Currently trying to work in Python3 and use absolute imports to import one module into another but I get the error ModuleNotFoundError: No module named '__main__.moduleB'; '__main__' is not a package. Consider this project structure:

proj     __init__.py3 (empty)     moduleA.py3     moduleB.py3 

moduleA.py3

from .moduleB import ModuleB ModuleB.hello() 

moduleB.py3

class ModuleB:     def hello():         print("hello world") 

Then running python3 moduleA.py3 gives the error. What needs to be changed here?

like image 670
mpseligson Avatar asked Aug 01 '17 19:08

mpseligson


People also ask

What is Python __ main __?

__main__ is the name of the environment where top-level code is run. “Top-level code” is the first user-specified Python module that starts running. It's “top-level” because it imports all other modules that the program needs. Sometimes “top-level code” is called an entry point to the application.

What causes import error?

File size That can be caused by too many fields or records in the file, too many columns, or too many rows. The import error can be caused by limits set by the program using the file or the amount of available memory on the system.


1 Answers

.moduleB is a relative import. Relative only works when the parent module is imported or loaded first. That means you need to have proj imported somewhere in your current runtime environment. When you are are using command python3 moduleA.py3, it is getting no chance to import parent module. You can:

  • from proj.moduleB import moduleB OR
  • You can create another script, let's say run.py, to invoke from proj import moduleA

Good luck with your journey to the awesome land of Python.

like image 167
Md. Sabuj Sarker Avatar answered Sep 24 '22 17:09

Md. Sabuj Sarker