developing a new package and getting ModuleNotFoundError: No module named - python

I was writing a little application where I wanted to create a module containg a small group of classes, but when I try to import the classes from the main application, I get the error:
my_project python3 main.py
1
Traceback (most recent call last):
File "main.py", line 2, in <module>
import receivers
File "/home/mario/Documents/python/my_project/receivers/__init__.py", line 2, in <module>
from icinga import Icinga
ModuleNotFoundError: No module named 'icinga'
The file in the project are:
├── main.py
└── receivers
├── icinga.py
├── __init__.py
where main.py
#!/usr/bin/env python
import receivers
icinga = receivers.icinga.Icinga()
the file receivers/icinga.py
class Icinga:
def __init__(self):
print("I'm Icinga!")
the file receivers/__init__.py
print('1')
from icinga import Icinga
print('2')
Can someone please tell me what I do wrong?
Thanks in advance

If you just want to import the Icinga class, you can do it as
from receivers.icinga import Icinga
If you want to call the import statement on receivers, you should alter the init.py, on 2nd line, to:
from .icinga import Icinga
I reproduced your problem here, and was able to solve it like that.
Edit:
Doing this second thing (on __init__.py), you would be able to call it on the main.py as:
import receivers
receivers.icinga.Icinga()

Related

Can't access modules of my python package [duplicate]

This question already has answers here:
Import a file from a subdirectory?
(13 answers)
Closed 11 months ago.
contents of "init.py" file inside "handlers" folder:
from handlers import client
from handlers import admin
from handlers import other
and the content of the "main.py" file looks like this inside the main folder:
from aiogram.utils import executor
from datetime import datetime
from create_bot import dp
from handlers import client, admin, other
client.register_handlers_client(dp)
other.register_handlers_other(dp) #last one!
async def on_startup(_):
start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("Bot went online at " + start_time)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True, on_startup=on_startup)
the file structure of my project (this is a telegram bot) looks like this:
test_bot ---> __pycache__
|
|---> handlers ---> client.py, other.py,__init__.py
|
'---> main ---> main.py,config_testbot.py,etc...
when running the "main.py" file in cmd it outputs the following:
Traceback (most recent call last):
File "main.py", line 5, in <module>
from handlers import client, admin, other
ModuleNotFoundError: No module named 'handlers'
And so, how to run the file "main.py" without error? How to replace
from handlers import client, admin, other
so that everything works without errors?! My python version 3.8.10.
I hope you can help me with this problem, thanks in advance!
TLDR;
from handlers.client import *
from handlers.admin import *
from handlers.other import *
If I understood correctly, your question is 'How to import a file from a subdirectory'
I am reading from:
docs
stackoverflow
If you are not using Python 3.3 or upwards create a blank file called __init__.py in the subfolder.
Apparently after Python 3.3 you no longer need the __init__.py file.
And then,
Instead of trying to import handlers which I understood to be the subfolder, try to import the file from the subfolder referring to it as
from subfolder.filename import foo
in your case:
from handlers.client import foo

import on Python doesn't work as expected

Although the variable should be imported, I get "name X is not defined" exception.
main.py
from config import *
from utils import *
say_hello()
utils.py
from config import *
def say_hello():
print(config_var)
config.py
from utils import *
config_var = "Hello"
Trying to run "main.py":
Traceback (most recent call last):
File "main.py", line 3, in
say_hello()
File "C:\Users\utils.py", line 3, in say_hello
print(config_var)
NameError: name 'config_var' is not defined
What happened here? Why some_var is not accessible from utils.py?
You are importing config in util and util in config which will causing this error(create cross loop). remove from utils import * from config.py and then try this.
And in main.py you don't need to import the from config import * unless you are using variables from config directly in your main()
you should also import config.config_var, since this variable belongs to that specific module
You are creating to many import statements perhaps try the following below, but also you need to define a parameter in utils.py if you are passing a parameter through there.
In utils.py we require a parameter to be passed since you want to print out the appropriate value, In config.py you are defining a value. Then in main.py as discussed before using the wildcard operator "*" isn't entirely good in this situation then in order to call the respective functions you need to address them through their file name
In utils.py :
def say_hello(config_var):
print(config_var)
In config.py
config_var = "Hello"
Then in main.py
import config as cn
import utils as ut
ut.say_hello(cn.config_var)
Check out this thread for how to write python modules as well How to write a Python module/package?

ModuleNotFoundError: No module named 'gothonweb2' in python

My error is like
(base) C:\Users\lenovo\projects\gothonweb2>python bin/app.py
Traceback (most recent call last):
File "bin/app.py", line 2, in <module>
from gothonweb2 import map
ModuleNotFoundError: No module named 'gothonweb2'
The project directory is
C:\Users\lenovo\projects\gothonweb2
bin
__init__.py
app.py
gothonweb2
__init__.py
web.py
templates
layout.html
show_room.html
you_died.html
tests
__init__.py
app_tests.py
map_tests.py
tools.py
The code in bin/app.py is :
import web
from gothonweb2 import map
import urllib.request
urls=(
'/game','GameEngine',
'/','Index',
)
app=web.application(urls,globals())
#Title hack so that debug mode works with sessions
if web.config.get('_session') is None:
store=web.session.DiskStore('sessions')
session=web.session.Session(app,store,initializer={'room':None})
web.config._session=session
else:
session=web.config._session
render=web.template.render('templates/',base="layout")
class Index(object):
def GET(self):
#this is use to"setup"the session with starting values
session.room=map.START
web.seeother("/game")
class GameEngine(object):
def GET(self):
if session.room:
return render.show_room(room=session.room)
else:
return render.you_died()
def POST(self):
form=web.input(action=None)
#there is a bug here,can you fix it?
if session.room and form.action:
session.room=session.room.go(form.action)
web.seeother("/game")
if __name__=="__main__":
app.run()
I got the error just as above. Also the project's path and the import gothonweb2 part are also above. I don't know why it returns 'No module named 'gothonweb2''. Can someone help me?

python flask "from package.module" error

there're an open source forum(flaskbb - github) writen by flask, they use from flaskbb.user.models import User in /flaskbb/user/models.py to load User class .
I was trying to imitate that so my project 'dawntime' file structure like this:
dawntime
-__init__.py
-app.py
-public
--__init__.py
--index.py
app.py:
from flask import Flask
from dawntime.public import index
...
both __init__.py file are empty and I really think it's not important about how the file /dawntime/public/index.py is, because of an error occured in line 2 of app.py, complier showed this:
Traceback (most recent call last):
File "app.py", line 2, in
from dawntime.public import index
ImmportError: No module named dawntime.public
would anyone tell what's wrong with that? tks in advanced
app.py is already in the dawntime directory, so instead I think you need
from public import index

how to import the blog.py(i import the 'blog' folder)

my dir location,i am in a.py:
my_Project
|----blog
|-----__init__.py
|-----a.py
|-----blog.py
when i 'from blog import something' in a.py , it show error:
from blog import BaseRequestHandler
ImportError: cannot import name BaseRequestHandler
i think it import the blog folder,not the blog.py
so how to import the blog.py
updated
when i use 'blog.blog', it show this:
from blog.blog import BaseRequestHandler
ImportError: No module named blog
updated2
my sys.path is :
['D:\\zjm_code', 'D:\\Python25\\lib\\site-packages\\setuptools-0.6c11-py2.5.egg', 'D:\\Python25\\lib\\site-packages\\whoosh-0.3.18-py2.5.egg', 'C:\\WINDOWS\\system32\\python25.zip', 'D:\\Python25\\DLLs', 'D:\\Python25\\lib', 'D:\\Python25\\lib\\plat-win', 'D:\\Python25\\lib\\lib-tk', 'D:\\Python25', 'D:\\Python25\\lib\\site-packages', 'D:\\Python25\\lib\\site-packages\\PIL']
zjm_code
|-----a.py
|-----b.py
a.py is :
c="ccc"
b.py is :
from a import c
print c
and when i execute b.py ,i show this:
> "D:\Python25\pythonw.exe" "D:\zjm_code\b.py"
Traceback (most recent call last):
File "D:\zjm_code\b.py", line 2, in <module>
from a import c
ImportError: cannot import name c
When you are in a.py, import blog should import the local blog.py and nothing else. Quoting the docs:
modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script
So my guess is that somehow, the name BaseRequestHandler is not defined in the file blog.py.
what happens when you:
import blog
Try outputting your sys.path, in order to make sure that you have the right dir to call the module from.

Categories

Resources