Logging; ImportError: cannot import name 'get_logger' from 'logger' - python

I've got a Python script from a friend who is not in available at the moment.
Unfortunately i am not able run it.
Error:
ImportError: cannot import name 'get_logger' from 'logger' (C:\Users\MyName\AppData\Local\Programs\Python\Python311\Lib\site-packages\logger\__init__.py)
I can locate the file __init__.py at the mentioned path.
Part of the script which causes this error:
import time
import sys
import requests
from bs4 import BeautifulSoup
import pandas as pd
from requests.api import post
import os
import traceback
from logger import get_logger #<----- Error
from datetime import date
dir_path = os.path.dirname(os.path.realpath(__file__))
logging = get_logger(dir_path)
logger = logging.getLogger(__name__)
logger = logging.getLogger()
[...]
Code of __init__.py:
import logging
import logging.config
import os
import sys
import types
logging.getLogger('paramiko').setLevel(logging.WARNING)
logging.getLogger('requests').setLevel(logging.WARNING)
config_file = os.path.join(os.path.dirname(__file__), 'logging.conf')
logging.config.fileConfig(config_file, disable_existing_loggers=False)
logger = logging.getLogger()
def error(self, msg, *args, **kwargs):
self.error(msg, *args, **kwargs)
sys.exit(1)
logger.interrupt = types.MethodType(error, logger)
logger.info = logger.info
logger.warn = logger.warn
I hope you guys can help me to solve this issue.
Thanks!
What i tried
Googled ImportError: cannot import name 'get_logger' from 'logger' - Answere was based on another issue (ImportError: cannot import name 'getLogger')
Tried to directly import logging instead of logger
No idea what else i should try since i usually do not develope (Hi from sales)

Related

How to debug VSCODE python using local packages

import logging
import sys
import os
from LoggingHelper.main import LoggingHelper <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
from LoggingHelper.models import logDataclass as ldc <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
from .configs.project_configs import *
kafka_config = {}
from fastapi import FastAPI, Request <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
from fastapi.responses import JSONResponse <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
import fastapi <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
import azure.functions as func <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
import nest_asyncio
from starlette.middleware import Middleware <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
from starlette.middleware.cors import CORSMiddleware <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
nest_asyncio.apply()
from TSAuthHelper import FastAPIAuthHelper <-- Import "LoggingHelper.main" could not be resolvedPylancereportMissingImports
import json
import os
import time
import traceback
import pickle
I have a local library/package in ".python_packages\lib\site-packages" called "LoggingHelper", "fastapi", "starlette/middleware", etc. But I can't compile those in VSCODE.
They work just fine if I publish them all to Azure Functions, but not locally. I need to debug them locally on my VSCODE.
I have been trying to read everything I can, change the interpreter, etc. But I'm not a developer and need some guidance.
from .python_packages/fastapi import FastAPI
from fullpath/.python_packages/fastapi import FastAPI
nothing works.
When running locally you may need to specify the major version of Python you intend to use. Normally on Linux the first line of a Python3 program would be something like:
#!/usr/bin/python3
import os
...
Then before importing modules that are in an unusual location you might need to add a line:
sys.path.append("/fullpath/to/custom/modules/dir")
then you should be able to import modules that are in that directory.

Python module won't import when class instance is called in another script

I have two scripts in a folder called booking (constants.py and booking.py).
I then have a file called run.py in the parent folder of the booking folder.
I import constants in my booking.py script and it works fine. Then I import booking in my run.py and it works, but the constants module does not import and I receive the error.
File "/Users/user/Desktop/coding/selenium_tute/booking/booking.py", line 4, in <module>
import constants as const
ModuleNotFoundError: No module named 'constants'
Here is the booking.py script
from selenium import webdriver
from selenium.webdriver.common.by import By
import os
import constants as const
import sys
#BASE_URL = "https://www.booking.com"
class Booking(webdriver.Chrome):
def __init__(self, driver_path=r"/usr/local/bin/chromedriver", teardown=False):
self.driver_path= driver_path
os.environ['PATH'] += self.driver_path
self.teardown = teardown
super(Booking, self).__init__()
self.implicitly_wait(15)
self.maximize_window()
def __exit__(self, exc_type, exc_val, exc_tb):
if self.teardown:
self.quit()
def land_first_page(self):
self.get(const.BASE_URL)
def change_currency(self, currency=None):
currency_element = self.find_element(By.CSS_SELECTOR, 'button[data-tooltip-text="Choose your currency"]')
currency_element.click()
print(const.BASE_URL)
Here is the run.py script
from booking.booking import Booking
with Booking(teardown=False) as bot:
bot.land_first_page()
bot.change_currency()
Any help would be much appreciated

How could I use same python logger in different files?

in the main.py I configure the python logger like this:
import func
import os.path as osp
import logging
logfile = '{}.log'.format(time.strftime('%Y-%m-%d-%H-%M-%S'))
logfile = osp.join('./res/', logfile)
FORMAT = '%(levelname)s %(filename)s(%(lineno)d): %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT, f ilename=logfile)
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
This works fine in this main.py file, but I still need the use the same logger in my func.py file which is a module imported by my main.py. I still need to print the log message to the screen together with the same logger file as in main.py. How could I do this ?
You can just define it and import it as a simple solution. When you import you do have access to your definitions in the other file... Just look at the imports in the code you posted.

python: how to import a module

I'm a newbie in using Python.
What I need is simple: import a module dynamically.
Here is my little test:
#module
class Test:
def func(self, id, name):
print("Your ID: " + str(id) + ". Your name: " + name)
return
I put this class in a file named my_module.py and the path of the file is: c:\doc\my_module.py.
Now I create a new python project to import the file above.
Here is what I do:
import sys
module = sys.path.append(r'c:\doc\my_module.py')
myClass = module.__class__
print(myClass)
However, I got this result:
<class 'NoneType'>
Why can't I get Test?
Is it because the way to import a module is wrong or because I need to do some config to import a module?
You're doing it wrong. Here's how you should import your module with sys.path.append:
import sys # import sys
sys.path.append(r'c:\doc\') # add your module path to ``sys.path``
import my_module # now import your module using filename without .py extension
myClass = my_module.Test # this is how you use the ``Test`` class form your module
try this:
import sys
sys.path.append(r'c:\doc\') # make sure python find your module
import my_module # import your module
t = my_module.Test() # Initialize the Test class
t.func(1, 'test') # call the method
The way to import a module is through the import command. You can specify the path with sys as a directory. You also need to instantiate the class within the module (through the my_module.Test()). See the following:
import sys
sys.path.append(r'c:\doc\\')
import my_module
myObj = my_module.Test()
myClass = myObj.__class__
print(myClass)

ImportError: No module named control

I have a celery app, my files like this:
/fetcher.py
/mirad
celery.py
fetcher_tasks.py
in celery.py i was import fetcher_tasks.py
and in fetcher.py i call a task from fetcher_tasks.py
i want to import celery.control in fetcher.py but i can't do it, how i can do this work?
this is a part of my fetcher code:
from __future__ import absolute_import
import mirad.fetcher_tasks as tasks
from mirad.models.models import SourceModel
from mirad.settings import *
from mirad.celery.control import inspect
parse_feed_tasks = list()
def fetch():
for source in SourceModel.objects(active=True):
a = tasks.parse_feed.delay(source)
Looks like you mix celery.py in your project which is used to start Celery app with celery package from which you can import necessery functions.
You should import inspect function from celery.task.control package.
from __future__ import absolute_import
import mirad.fetcher_tasks as tasks
from mirad.models.models import SourceModel
from mirad.settings import *
from celery.task.control import inspect
parse_feed_tasks = list()
def fetch():
for source in SourceModel.objects(active=True):
a = tasks.parse_feed.delay(source)

Categories