Что значит no module named

Как исправить ошибку «ImportError: no module named . » в Python?

Как правильно исправить эту ошибку ImportError?

у меня есть следующая структура каталогов:

а я в директории

теперь, если я типа

Я мгновенно получаете

The ./programs/my_python_program.py содержит следующую строку:

Я не могу понять, почему python не найдет ./foo/tasks.py — это есть.

если я делаю это из оболочки Python, то это работает:

это только не работает, если я вызываю его через python ./programs/my_python_program.py сценарий.

6 ответов:

Python не добавляет текущий каталог в sys.path , но скорее каталог, в котором находится скрипт. Добавить /home/bodacydo/work/project или sys.path или $PYTHONPATH .

у вас есть файл с названием __init__.py в каталоге foo? Если нет, то python не распознает foo как пакет python.

посмотреть пакетов в учебнике python для получения дополнительной информации.

добавить скрипт под названием run.py in /home/bodacydo/work/project и редактировать его так:

(вместо main() с эквивалентным методом в my_python_program .)

  • на /home/bodacydo/work/project
  • выполнить run.py
  • объяснение: Поскольку python добавляет к PYTHONPATH путь скрипт, из которого он запускается, работает run.py будет добавлять /home/bodacydo/work/project . И вуаля, import foo.tasks будут найдены.

    пример решения для добавления библиотеки в PYTHONPATH.

    добавьте следующую строку в ваш

    /.bashrc или просто запустить его напрямую:

    затем свяжите необходимую библиотеку с вашим

    Источник

    No module named when using PyInstaller

    I try to compile a Python project under Windows 7 using PyInstaller. The project works fine, there are no issues, however when I try to compile it the result doesn’t work. Though I get no warnings during compilation there are many in the warnmain.txt file in the build directory: warnmain.txt

    I don’t really understand those warnings, for example «no module named numpy.pi» since numpy.pi is no module but a number. I never tried to import numpy.pi . I did import numpy and matplotlib explicitly. In addition I’m using PyQt4. I thought the error might be related to those libraries.

    However I was able to compile a simple script which uses numpy succesfully:

    Successfully here means that the created executable file actually showed the desired output. However there is also a warnmain.txt file created which contains exactly the same ‘warnings’ as the one before. So I guess the fact that compiling my actual project does not give any success is not (or at least not only) related to those warnings. But what else could be the error then? The only output during compilation are ‘INFO’s and none of the is a negative statement.

    I did not specify an additional hook directory but the hooks where down using the default directory as far as I could read from the compile output, e.g. hook-matplotlib was executed. I could not see any hook for numpy neither could I for my small example script but this one worked. I used the following imports in my files (not all in the same but in different ones):

    Since PyInstaller does not give any errors/warnings I could not figure out if the problem is related to the libraries or if there is something else to be considered.

    Источник

    Python error «ImportError: No module named»

    Python is installed in a local directory.

    My directory tree looks like this:

    My code is in here:

    To run the example, I write python mountain.py , and in the code I have:

    And I get the error:

    I have already checked sys.path and there I have the directory /site-packages . Also, I have the file __init__.py.bin in the toolkit folder to indicate to Python that this is a package. I also have a __init__.py.bin in the examples directory.

    I do not know why Python cannot find the file when it is in sys.path . Any ideas? Can it be a permissions problem? Do I need some execution permission?

    32 Answers 32

    Based on your comments to orip’s post, I guess this is what happened:

    1. You edited __init__.py on windows.
    2. The windows editor added something non-printing, perhaps a carriage-return (end-of-line in Windows is CR/LF; in unix it is LF only), or perhaps a CTRL-Z (windows end-of-file).
    3. You used WinSCP to copy the file to your unix box.
    4. WinSCP thought: «This has something that’s not basic text; I’ll put a .bin extension to indicate binary data.»
    5. The missing __init__.py (now called __init__.py.bin ) means python doesn’t understand toolkit as a package.
    6. You create __init__.py in the appropriate directory and everything works. ?

    have a __init__.py ?

    To make import walk through your directories every directory must have a __init__.py file.

    I ran into something very similar when I did this exercise in LPTHW; I could never get Python to recognise that I had files in the directory I was calling from. But I was able to get it to work in the end. What I did, and what I recommend, is to try this:

    (NOTE: From your initial post, I am assuming you are using an *NIX-based machine and are running things from the command line, so this advice is tailored to that. Since I run Ubuntu, this is what I did)

    Change directory (cd) to the directory above the directory where your files are. In this case, you’re trying to run the mountain.py file, and trying to call the toolkit.interface.py module, which are in separate directories. In this case, you would go to the directory that contains paths to both those files (or in other words, the closest directory that the paths of both those files share). Which in this case is the toolkit directory.

    When you are in the tookit directory, enter this line of code on your command line:

    This sets your PYTHONPATH to «.», which basically means that your PYTHONPATH will now look for any called files within the directory you are currently in, (and more to the point, in the sub-directory branches of the directory you are in. So it doesn’t just look in your current directory, but in all the directories that are in your current directory).

    After you’ve set your PYTHONPATH in the step above, run your module from your current directory (the toolkit directory). Python should now find and load the modules you specified.

    Hope this helps. I was quite frustrated with this myself.

    Источник

    No module named

    ModuleNotFoundError: No module named ‘fastai’
    Появилась такая проблема! Скачал при помощи pip модуль fastai pip install fastai Но выходит в.

    ModuleNotFoundError: No module named ‘pyaudio’
    И так и сяк пробовал установить PyAudio, ничего не получается. Вот ошибка которую выдает программа.

    Ошибка ModuleNotFoundError: No module named ‘pyautogui’ при импорте pyautogui
    Все установлено, но при импорте модуля выдает ошибку. С чем это может быть связано? pip install.

    PyQt5 Error while finding module specification for ‘PyQt5.uic.pyuic’ (ModuleNotFoundError: No module named ‘PyQt
    В общем поставил pyqt5 и python3.7 пишу в консоль python -m PyQt5.uic.pyuic Выдает ошибку Error.

    Решение

    сразу не с того начал, это яма. начни с основ и привет мир, парсинг строк, перевороты, листкомпс, генэксп, словари и далее по списку.

    Что за помор какой-то с этими ботами? Купил ардуино — первым делом поморгал светодиодом. Начал учить какой-то язык — написал хэлловорлд. Но! Начал учить питон — первым делом надо написать бота. Трындец

    iSmokeJC, сам в шоке. Может они все какую-то книгу или видео смотрят, где это советуют? Где источник этой заразы, чтобы выжечь каленым железом?

    Такие основы я в целом знаю, а вот подключение модулей у меня вызвало проблемы, хотя я это тоже считаю за основу языка, поэтому и задал вопрос)) У меня также было и с Colorama, а бот мне показался самой удобной наглядной практикой.

    Не вижу в этом ничего грешного, если понимаешь синтаксис в целом. Да и бот не для спама, а просто как «автоответчик» в сообществе тестировался.

    Добавлено через 9 минут

    При запуске скрипта PyCharm выдаёт «No module named Module»
    Здравствуйте, товарищи формучане! Вчера начал изучать великолепный язык под названием Python и.

    No module named ‘random’
    Здравствуйте! Нужна помощь! С другом хотим создать совместный проект, он на C# я на python.

    No module named ‘telepot’
    Здравствуйте, как подключить библиотеку telepot? написала в командной строке: pip install telepot.

    No module named ‘telepot’
    Установил модуль telepot : sudo pip install telepot sudo pip install telepot —upgrade .

    No module named models
    импортировал как надо, но все равно ругается, я новичок в django, подскажите добрые люди в чем.

    ImportError: No module named ‘six’
    Добрый день. Изучаю новую библиотеку питона Matplotlib. Во время компиляции кода from pylab.

    Источник

    Import Errors in Python: No Module Named “Module_Name” For VS Code

    You may have come across the dreaded import error in python like the one below:

    This is actually a simple error you can fix in no time. This may usually be a simple fix you can make through Visual Studio Code.

    Before anything I highly recommend you to work with a virtual environment like Anaconda to manage all your packages.

    Firstly, open up visual studio code and in your terminal check whether you are in your virtual environment. You can move into your virtual environment by typing in ‘conda activate (virtual environment name)’. This is shown below.

    But as you can see even though you have moved into your virtual environment, the python interpreter is still pointing to your base environment instead of your virtual environment. This is shown below.

    If so hold ‘Ctrl+Shift+P’ in Windows or ‘Command+Shift+P’ in Mac to open up the context menu in Visual Studio Code. There search for ‘Python: Select Interpreter’

    Here you have the option of selecting your python interpreter the project is currently pointing at. Since it was pointed to the conda base environment, you can go and select the virtual environment that you installed your packages for the project. In this case it ‘Python 3.9.2 64 bit (‘venv’: conda)’ as shown below.

    Once you selected that, you will see that your interpreter has shifted to point to your virtual environment.

    So there you have it. Once you run your project, everything will be working fine and no more import errors you will have to worry about.

    Источник

    Читайте также:  Что значит хороший юрист
    Оцените статью