- Не Запускает проект Python через консоль с ошибкой ModuleNotFoundError: No module named?
- Django ModuleNotFoundError: No module named ‘blog.urls’
- 2 ответа 2
- Всё ещё ищете ответ? Посмотрите другие вопросы с метками python python-3.x django или задайте свой вопрос.
- Похожие
- Подписаться на ленту
- Python — ModuleNotFoundError: No module named
- 5 Answers 5
- Python DNS module import error
- 15 Answers 15
- ModuleNotFoundError: No module named ‘__main__.config’; ‘__main__’ is not a package
- 1 ответ 1
Не Запускает проект Python через консоль с ошибкой ModuleNotFoundError: No module named?
Не Запускает проект Python через консоль с ошибкой
from Chip88.Chip8 import *
ModuleNotFoundError: No module named ‘Chip88’
Если запускаю через Pycharm запускает все нормально.
Дерево проекта такое:
-Chip8
-chip8/Chip88
-chip8/Chip88/main.py
-chip8/Chip88/Interface.py
-chip8/Chip88/Chip8.py
-chip8/Chip88/__init__.py
-chip8/__init__.py
При запуске main.py ругается на файл Chip8 при строке from Chip88.Chip8 import *
Как исправить?
- Вопрос задан более двух лет назад
- 21249 просмотров
либо, если вам так надо вызывать main.py напрямую из сердца пакета, пишите просто from Chip8 import *
Но тут всё антипаттерн на антипаттерне : )
Файл, который вы запускаете должен находиться в корне проекта, иначе нет смысла в той структуре пакетов, которую вы создали. То есть, дерево должно быть такое:
Теперь у вас папка с проектом chip8 , в ней основной файл main.py и один пакет chip88 . Тогда в файле main.py импорт из chip8.py должен выглядеть следующим образом:
from chip88.chip import *
Кстати, import * — это антипаттерн, так лучше не делать. Импортируйте только то, что вы намерены использовать в этом модуле.
Также обратите внимание, что я убрал заглавные буквы из всех названий файлов и папок. С заглавной буквы в питоне принято начинать только имена классов
Источник
Django ModuleNotFoundError: No module named ‘blog.urls’
Подскажите где ошибка, почему не могу запустить?
2 ответа 2
В файле urls.py (который НЕ blog/urls.py) в строке path(», include(‘blog.urls’)) вы пытаетесь сделать переход на домашнюю страницу сайта, я рекомендую вам попробовать обойтись без include(), т.к. это весьма плохая практика, которая приводит к некорректной работе приложения. Просто сделайте так: path(‘здесь можете либо оставить пустые кавычки, либо вписать свой url’, ваша_функция) импортируйте вьюху из этой же директории и сделайте роутинг через неё.
Проверь есть ли у тебя файл __init__.py в папке blog. Настоятельно советую следовать оф. документации при первом знакомстве с django: https://docs.djangoproject.com/en/2.2/intro/tutorial01/
Всё ещё ищете ответ? Посмотрите другие вопросы с метками python python-3.x django или задайте свой вопрос.
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.6.10.39473
Источник
Python — ModuleNotFoundError: No module named
I’m new in Python and I’m having the following error with this simple example:
This is my project structure:
And this is the error when I execute the src/main.py file:
If I move the main.py file to the root and then I execute this file again, works. but is not working inside src/ directory
This is my main.py :
Note: When I execute the same code from Pycharm is working fine, but not from my terminal.
5 Answers 5
Your PYTHONPATH is set to the current directory from the program you execute. So if you’re executing something inside a directory src , it will never be able to find the directory lib because it’s outside the path. There’s a few choices;
- Just move lib/ into src/ if it belongs to your code. If it’s an external package, it should be pip installed as Henrique Branco mentioned.
- Have a top-level script outside of src/ that imports and runs src.main . This will add the top-level directory to python path.
- In src/main.py modify sys.path to include the top-level directory. This is usually frowned upon.
- Invoke src/main.py as a module with python -m src.main which will add the top-level directory to the python path. Kind of annoying to type, plus you’ll need to change all your imports.
If I may add to MarkM’s answer, if you wanted to keep your current directory structure and still make it work, you could add a setup.py in your root dir, where you can use setuptools to create a package you could install.
If your file had something along the lines of:
And then you do pip install [—user] -e path/to/directory you’ll get an «editable package» which will effectively a symlink to the package in your development directory, so any changes you make will not require a reinstall (unless of course you rejig package structure or add/remove/edit entry points).
This does assume your src/main.py has a main function.
You’ll also need __init__.py files in your «package» directories, even in Python3, as otherwise Python assumes these are namespace packages (Won’t go into detail) and the find_packages() call won’t find them.
This will also allow your relative imports to work. Absolute imports will only work when invoking the script from your entry point but not when calling the script directly in your development directory.
Источник
Python DNS module import error
I have been using python dns module.I was trying to use it on a new Linux installation but the module is not getting loaded. I have tried to clean up and install but the installation does not seem to be working.
Updated Output of python version and pip version command
Thanks a lot for your help.
Note:- I have firewall installed on the new machine. I am not sure if it should effect the import. but i have tried disabling it and still it does not seem to work.
15 Answers 15
I ran into the same issue with dnspython.
My solution was to build the source from their official GitHub project.
So my steps were:
After doing this, I was able to import the dns module.
EDIT
It seems the pip install doesn’t work for this module. Install from source as described.
I solved this by uninstalling and then re-installing the dnspython module with PIP.
After the long list of files within pycache, type y to continue with the uninstall. After complete type:
I then ran my script and the errors were resolved.
You could also install the package with pip by using this command:
pip install git+https://github.com/rthalley/dnspython
I installed dnspython 1.11.1 on my Ubuntu box using pip install dnspython . I was able to import the dns module without any problems
I am using Python 2.7.4 on an Ubuntu based server.
On Debian 7 Wheezy, I had to do:
even if python-dns package was installed.
Very possible the version of pip you’re using isn’t installing to the version of python you’re using. I have a box where this is the case.
If it looks like pip doesn’t match your python, then you probably have something like the multiple versions of python and pip I found on my box.
As long as I use /home/student/class/bin/pip (2.7 that matches my python version on that box), then my imports work fine.
There’s probably a better way to do this, I’m still learning my way around too, but that’s how I solved it — hope it helps!
I faced the same problem and solved this like i described below: As You have downloaded and installed dnspython successfully so
- Enter into folder dnspython
- You will find dns directory, now copy it
- Then paste it to inside site-packages directory
That’s all. Now your problem will go
If dnspython isn’t installed you can install it this way :
- go to your python installation folder site-packages directory
- open cmd here and enter the command : pip install dnspython
Now, dnspython will be installed successfully.
This issue can be generated by Symantec End Point Protection (SEP). And I suspect most EPP products could potentially impact your running of scripts.
If SEP is disabled, the script will run instantly.
Therefore you may need to update the SEP policy to not block python scripts accessing stuff.
I installed DNSpython 2.0.0 from the github source, but running ‘pip list’ showed the old version of dnspython 1.2.0
It only worked after I ran ‘pip uninstall dnspython’ which removed the old version leaving just 2.0.0 and then ‘import dns’ ran smoothly
One possible reason here might be your script have wrong shebang (so it is not using python from your virtualenv). I just did this change and it works:
Or ignore shebang and just run the script with python in your venv:
I was getting an error while using «import dns.resolver». I tried dnspython, py3dns but they failed. dns won’t install. after much hit and try I installed pubdns module and it solved my problem.
In my case, I hava writen the code in the file named «dns.py», it’s conflict for the package, I have to rename the script filename.
ok to resolve this First install dns for python by cmd using pip install dnspython
(if you use conda first type activate and then you will go in base (in cmd) and then type above code) it will install it in anaconda site package ,copy the location of that site package folder from cmd, and open it . Now copy all dns folders and paste them in python site package folder. it will resolve it .
actually the thing is our code is not able to find the specified package in python\site package bcz it is in anaconda\site package. so you have to COPY IT (not cut).
I have faced similar issue when importing on mac.i have python 3.7.3 installed Following steps helped me resolve it:
- pip3 uninstall dnspython
- sudo -H pip3 install dnspython
Источник
ModuleNotFoundError: No module named ‘__main__.config’; ‘__main__’ is not a package
Есть следующая структура проекта:
При запуске python run.py:
В bot.py вот такие импорты:
Я знаю, что можно перенести db.py в папку telegram_bot и сделать абсолютный импорт, но мне важна именно такая структура проекта, помогите пожалуйста.
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 должен его искать:
Предупреждаю, что это временное решение.
Настоятельно рекомендую переделать структуру проекта, чтобы этого избежать.
Источник