Python no module named main

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 
from .moduleB import ModuleB ModuleB.hello() 
class ModuleB: def hello(): print("hello world") 

You can’t use the leading ‘.’ in imports and have it work the way you want it to when you’re running the file directly with Python. You have to import the file. If you placed another file outside proj that had import moduleA in it, I believe you would see the output you’re expecting.

6 Answers 6

.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.

Foreword

I’m developing a project which in fact is a Python package that can be installed through pip, but it also exposes a command line interface. I don’t have problems running my project after installing it with pip install . , but hey, who does this every time after changing something in one of the project files? I needed to run the whole thing through simple python mypackage/main.py .

/my-project - README.md - setup.py /mypackage - __init__.py - main.py - common.py 

The different faces of the same problem

I tried importing a few functions in main.py from my common.py module. I tried different configurations that gave different errors, and I want to share with you with my observations and leave a quick note for future me as well.

Relative import

The first what I tried was a relative import:

from .common import my_func 

I ran my application with simple: python mypackage/main.py . Unfortunately this gave the following error:

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

The cause of this problem is that the main.py was executed directly by python command, thus becoming the main module named __main__ . If we connect this information with the relative import we used, we get what we have in the error message: __main__.common . This is explained in the Python documentation:

Note that relative imports are based on the name of the current module. Since the name of the main module is always __main__ , modules intended for use as the main module of a Python application must always use absolute imports.

When I installed my package with pip install . and then ran it, it worked perfectly fine. I was also able to import mypackage.main module in a Python console. So it looks like there’s a problem only with running it directly.

Читайте также:  Css background url attr

Absolute import

Let’s follow the advise from the documentation and change the import statement to something different:

from common import my_func 

If we now try to run this as before: python mypackage/main.py , then it works as expected! But, there’s a caveat when you, like me, develop something that need to work as a standalone command line tool after installing it with pip. I installed my package with pip install . and then tried to run it.

ModuleNotFoundError: No module named 'common' 

What’s worse, when I opened a Python console, and tried to import the main module manually ( import mypackage.main ), then I got the same error as above. The reason for that is simple: common is no longer a relative import, so Python tries to find it in installed packages. We don’t have such package, that’s why it fails.

The solution with an absolute import works well only when you create a typical Python app that is executed with a python command.

Import with a package name

There is also a third possibility to import the common module:

from mypackage.common import my_func 

This is not very different from the relative import approach, as long as we do it from the context of mypackage . And again, trying to run this with python mypackage/main.py ends similar:

ModuleNotFoundError: No module named 'mypackage' 

How irritating that could be, the interpreter is right, you don’t have such package installed.

The solution

For simple Python apps

Just use absolute imports (without the dot), and everything will be fine.

For installable Python apps in development

Use relative imports, or imports with a package name on the beginning, because you need them like this when your app is installed. When it comes to running such module in development, Python can be executed with the -m option:

-m mod : run library module as a script (terminates option list) 

So instead of python mypackage/main.py , do it like this: python -m mypackage.main .

Читайте также:  Инструкции if elif в python

Источник

ModuleNotFoundError — No module named ‘main’ when attempting to start service

My application performs flawlessly when I run it via python manage.py runserver . Yet it comes to a sudden halt when I attempt to deploy it to Google App Engine.

Traceback (most recent call last): File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app __import__(module) ModuleNotFoundError: No module named 'main' 

I’ve gone through numerous threads and I cannot find the problem. (For reference the dev_appserver.py emulator produces the same problem, which is a good thing).

runtime: python37 env: standard handlers: - url: /static static_dir: static/ - url: .* script: demosite.wsgi.main 

My wsgi.py file is located in the following path: demosite/wsgi.py and it’s contents look like this:

import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demosite.settings') main = get_wsgi_application() 
import os class AppSettings(object): GoogleCloudProject = os.getenv('GOOGLE_CLOUD_PROJECT') BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'say what?' DEBUG = True ALLOWED_HOSTS = [ '*' ] INSTALLED_APPS = [ 'anchor.apps.AnchorConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'demosite.urls' TEMPLATES = [ < 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': < 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], >, >, ] WSGI_APPLICATION = 'demosite.wsgi.main' try: import MySQLdb except ImportError: import pymysql pymysql.install_as_MySQLdb() if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): DATABASES = < 'default': < 'ENGINE': 'django.db.backends.mysql', 'NAME': 'webapp', 'USER': 'aasdeytst', 'PASSWORD': 'asdasygetasfasdfasd.', 'HOST': 'asdgiuasfivaasd', 'PORT': '3306' >> else: DATABASES = < 'default': < 'ENGINE': 'django.db.backends.mysql', 'NAME': 'webapp', 'USER': 'awthdsfhfdhdf', 'PASSWORD': 'asdasdasdagwdatwt', 'HOST': 'localhost', 'PORT': '3306' >> AUTH_PASSWORD_VALIDATORS = [ < 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', >, < 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', >, < 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', >, < 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', >, ] ANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = 'static' STATIC_URL = '/static/' CRISPY_TEMPLATE_PACK = 'bootstrap4' LOGIN_REDIRECT_URL = 'index' LOGIN_URL = 'login' SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_AGE = 1800 

What am I missing, what am I doing wrong? I’ve spent close on 4 hours trying to figure this problem out to no avail.

Источник

ModuleNotFoundError: No module named ‘__main__.config’; ‘__main__’ is not a package

введите сюда описание изображения

Есть следующая структура проекта: При запуске python run.py:

import subprocess if __name__ == '__main__': while True: p = subprocess.Popen(['python', 'telegram_bot/bot.py']).wait() if p: continue break 
ModuleNotFoundError: No module named '__main__.config'; '__main__' is not a package 
from .config import * from database.db import cursor, connection 

Я знаю, что можно перенести db.py в папку telegram_bot и сделать абсолютный импорт, но мне важна именно такая структура проекта, помогите пожалуйста.

Читайте также:  Спецсимвол корзина html css

1 ответ 1

Инструкция subprocess.Popen([‘python’, ‘telegram_bot/bot.py’]) запускает файл bot.py .

В нём у Вас находится инструкция from .config import * — относительный импорт.

Но относительный импорт нельзя использовать в файле, который Вы планируете запускать.
Вот выдержка из документации по этому поводу:

Note that relative imports are based on the name of the current module. Since the name of the main module is always «__main__» , modules intended for use as the main module of a Python application must always use absolute imports.

Обратите внимание, что относительный импорт основан на имени текущего модуля. Поскольку имя основного модуля всегда «__main__» , модули, предназначенные для использования в качестве основного модуля приложения Python, всегда должны использовать абсолютный импорт.

Замените относительный импорт на абсолютный:

При такой структуре проекта, от импорта database.db придётся отказаться, либо явно указывать путь, по которому Python должен его искать:

import sys sys.path.insert(0, r"path\to\database") from db import cursor, connection 

Предупреждаю, что это временное решение.
Настоятельно рекомендую переделать структуру проекта, чтобы этого избежать.

Источник

ModuleNotFoundError: What does it mean __main__ is not a package?

enter image description here

I am trying to run a module from the console. The structure of my directory is this: I am trying to run the module p_03_using_bisection_search.py , from the problem_set_02 directory using:

$ python3 p_03_using_bisection_search.py 
__author__ = 'm' from .p_02_paying_debt_off_in_a_year import compute_balance_after def compute_bounds(balance: float, annual_interest_rate: float) -> (float, float): # there is code here, but I have omitted it to save space pass def compute_lowest_payment(balance: float, annual_interest_rate: float) -> float: # there is code here, but I have omitted it to save space pass def main(): balance = eval(input('Enter the initial balance: ')) annual_interest_rate = eval(input('Enter the annual interest rate: ')) lowest_payment = compute_lowest_payment(balance, annual_interest_rate) print('Lowest Payment: ' + str(lowest_payment)) if __name__ == '__main__': main() 
__author__ = 'm' def compute_balance(balance: float, fixed_payment: float, annual_interest_rate: float) -> float: # this is code that has been omitted pass def compute_balance_after(balance: float, fixed_payment: float, annual_interest_rate: float, months: int=12) -> float: # Omitted code pass def compute_fixed_monthly_payment(balance: float, annual_interest_rate: float) -> float: # omitted code pass def main(): balance = eval(input('Enter the initial balance: ')) annual_interest_rate = eval( input('Enter the annual interest rate as a decimal: ')) lowest_payment = compute_fixed_monthly_payment(balance, annual_interest_rate) print('Lowest Payment: ' + str(lowest_payment)) if __name__ == '__main__': main() 
ModuleNotFoundError: No module named '__main__.p_02_paying_debt_off_in_a_year'; '__main__' is not a package 

I have no idea how to solve this issue. I have tried adding a __init__.py file, but it is still not working.

Источник

Оцените статью