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
Related
This question already has answers here:
Relative imports for the billionth time
(12 answers)
Closed 4 months ago.
i have a folder with a bot and a folder with a future api. The problem is that when I try to import a class from the database folder in the bot, it gives an error that this package does not exist. inits are all written, what could be wrong? Or how to fix it?
In the bot folder in the init, I do the import - from .database import GetCategories
Next in the api folder (top) I try to import this class into the main.py file - from bot import GetCategories
But I get an error - ModuleNotFoundError: No module named 'bot'
Example:
folder api:
main.py
code:
from fastapi import FastAPI
from bot import GetCategories
app = FastAPI()
#app.get("/get_categories/{auth_token}")
def read_item(auth_token: str):
i = GetCategories()
return 'test'
folder bot:
init code: from .database import GetCategories
folder database:
init code: from .categories import GetCategories
categories.py code:
class GetCategories:
print('done')
run main.py in folder api: uvicorn main:app --reload
example structure
Try:
from bot.database import GetCategories
But first you need to take main.py out right in the folder where bot directory is OR move bot directory to where main.py is, other wise you will need to make package of this database directory then import it.
My goal is to import code into three separate Flask servers. It's not going well. I am on python 3.10.4. I have read perhaps 10 different posts that say things like "put a __init__.py file in your folders" which I have done.
For context I'm not exactly new to Python but I've never learned the importing/module system properly.
I have three Flask servers that run scraping operations on different (but similar) websites. I need them to be separate for various reasons. Anyway, all three need to run the same procedure of getting an IP for a proxy from my proxy provider. For this I have some code:
# we don't need the details here so I snip it to save space
def get_proxy_ip(choice):
r = requests.get(download_list, headers={"Authorization": "Token " + token})
selected_proxy_ip = r.json()["results"][choice]["proxy_address"]
selected_proxy_port = r.json()["results"][choice]["port"]
print(selected_proxy_ip)
return selected_proxy_ip, selected_proxy_port
I want to use this function across all 3 of my Flask servers. Here are some various ways I've tried to import the code into one of the Flask servers:
scrapers/rentCanada/app.py
import requests
from flask import Flask, request, make_response
print("cats")
app = Flask(__name__)
print(__name__, __package__)
# from ..shared.ipgetter import get_proxy_ip
# from ..shared.checker import check_public_ip
# from scrapers.shared.ipgetter import get_proxy_ip
# from scrapers.shared.checker import check_public_ip
import shared.ipgetter as ipgetter
import shared.checker as checker
None of them work.
import shared.ipgetter as ipgetter yields:
cats
__main__ None
Traceback (most recent call last):
File "/home/rlm/Code/canadaAps/scrapers/rentCanada/app.py", line 10, in <module>
import shared.ipgetter as ipgetter
ModuleNotFoundError: No module named 'shared'
ModuleNotFoundError: No module named 'scrapers' yields: ModuleNotFoundError: No module named 'scrapers'
from ..shared.ipgetter import get_proxy_ip yields: ImportError: attempted relative import with no known parent package
At this point you need to see my folder structure.
/scrapers
..__init__.py
..setup.py
../rentCanada
.....__init__.py
.....app.py
../rentFaster
.....__init__.py
.....app.py
../rentSeeker
.....__init__.py
.....app.py
../shared
.....__init__.py
.....ipgetter.py
.....checker.py
I need to be able to use any of the app.py files as entry points.
I also tried setup.py with this:
from setuptools import setup, find_packages
setup(
name = 'tools',
packages = find_packages(),
)
followed by python setup.py install but that didn't make a "tools" import available in app.py like I wanted.
As a final note I suspect someone will tell me to use a blueprint. To me those look like a tool I'd use if I was adding a route. I'm not sure they're right for a simple function, but maybe I'm wrong.
My solution for now is to run Flask with python rentCanada/app.py from the /scrapers folder and use this code
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent)) # necessary so util folder is available
import requests
from flask import Flask, request, make_response
print("cats")
app = Flask(__name__)
print(__name__, __package__)
from util.ipgetter import get_proxy_ip
from util.checker import check_public_ip
So the program appends the app.py file folder's parent folder to the path. That makes the util folder (which used to be shared but had a naming conflict) available within the app.py file.
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()
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?
My project structure is as follows:
my_proj
---calculation
---cardata
---master
---my_proj
--- __init.py__
--- admin.py
--- settings.py
--- url.py
--- update_db_from_ftp.py ///// This is my custom file
In update_db_from_ftp.py I want to download an csv file from ftp and update the database(if necessary) once every day with cron.
But the problem is that I can't import model which I want to update. The model which I want to update is inside master folder in models.py file.
I try to import model as follows:
from master.models import ModelName
But I'm getting an error as follows:
Traceback (most recent call last):
File "update_db_from_ftp.py", line 6, in <module>
from master.models import ModelName
ImportError: No module named master.models
But I use the same model in cardata and calculation folder and I import it the same way as I try in update_db_from_ftp.py file, but there it works without problems.
Any idea how to solve it?
UDPATE
The structure of the master folder is as follows:
For using django code in an arbitrary external script, two things are needed:
Django should be setup (exactly what happens when you run django shell).
The root project should be in python path (not the inner folder with same name).
Here is sample code which will work irrespective of the location of the script (although if the script is not one-off, better to add it as management command):
import django
import os
import sys
sys.path.append("/path/to/my-proj/")
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my-proj.settings')
django.setup()
from master.models import ModelName
if __name__ == "__main__":
print(ModelName.objects.all())