0

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!

Иван
  • 3
  • 1
  • Maybe this is of help to you https://stackoverflow.com/questions/1260792/import-a-file-from-a-subdirectory –  Mar 29 '22 at 18:01

1 Answers1

0

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