I test following code to understand importing a custom python program and it works fine but when follow same process for importing custom logging module I see error.
Below works fine
#calculation.py
from mult import product
def add(a,b):
return a + b
if __name__== '__main__':
a = 10
b = 5
print(add(a,b))
print(product(a,b))
Now second program mult.py
# mult.py
def product(a,b):
return a * b
Below does not work, why?
#test_logger.py
import loggerforhousing
print("custom logs")
logger.info("this is info")
logger.error("this is error")
second program
#loggerforhousing.py
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s')
file_handler = logging.FileHandler('train_123.log') # store log files in artifacts directory
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
Error message
Traceback (most recent call last):
File "test_logger.py", line 3, in <module>
logger.info("this is info")
NameError: name 'logger' is not defined
Please help me figure out what I am missing.
In test_logger.py, declare logger as being part of loggerforhousing.py:
loggerforhousing.logger.info(“this is info”)
Or import logger explicitly (as done in your first snippet with product function):
from loggerforhousing import logger
Does it help?
Related
I have few common functions written in file a.py which is called from file b.py. And, also I have few common functions written in file b.py which is called from file a.py. but when I try to run these files I get error as unable to import name. Below is the code for reference.
I have just provided an example below, these files have common piece of code in real scenario which is specific to a functionality and that is the reason its being called from one another
a.py code below
from b import get_partner_id
def get_customer_id(tenant_id):
customer_id = tenant_id + "tenant_name"
return customer_id
def get_partner_details():
partnerid = get_partner_id()
data = {"partnerId": partnerid}
print(data)
b.py code below
from a import get_customer_id
def get_partner_id():
customer_id = get_customer_id("7687")
env = 'sandbox-all' + customer_id
return env
get_partner_id()
Below is the error for reference,
Traceback (most recent call last):
File "C:/testCases/b.py", line 1, in <module>
from a import get_customer_id
File "C:\testCases\a.py", line 2, in <module>
from b import get_partner_id
File "C:\testCases\b.py", line 1, in <module>
from a import get_customer_id
ImportError: cannot import name 'get_customer_id'
Testcode.py
import code
import unittest
class TestCode( unittest.TestCase ):
def test_simple( self ):
self.assertEqual( code.return_zero(),0 )
if __name__ == '__main__':
unittest.main()
code.py
def return_zero ():
return 0
expected ok result
but getting this below error
-----------------------------
Traceback (most recent call last):
File "C:++++++/.spyder-py3/testcode.py", line 6, in test_simple
self.assertEqual( code.return_zero(),0 )
AttributeError: 'Testcode' object has no attribute 'assertnotEqual'
----------------------------------------------------------------------
Ran 2 tests in 0.002s
FAILED (errors=2)
I don't understand how your code has output this error.
you need to import the return_code from the code module.
from:
import code
to:
from code import return_code
or:
from code import *
and then:
self.assertEqual(return_zero(),0 )
I'm upgrading a python 2.7 code to python 3.6, but every time I'm trying to write something on console using logging I get this error
TypeError: a bytes-like object is required, not 'str'
I've read most of the similiar questions with this but none of them has worked.
# mainTest.py module
from config import logger
log = logger.getLogger(__file__)
def function():
message = "testing"
log.info(message)
# code
# logger.py
import logging
import os
import classpathDir as cf
def getLogger(loggerForFile):
logger = logging.getLogger(os.path.basename(loggerForFile))
if not logger.handlers:
logging.basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%d/%m/%Y %I:%M:%S %p', filename=cf.ROOT_DIR + "/output/processing.log",
filemode='wb', level=logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
# set a format which is simpler for console use
formatter = logging.Formatter('%(asctime)s %(name)-12s: %(levelname)-8s %(message)s',
datefmt='%d/%m/%Y %I:%M:%S')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logger.addHandler(console)
return logger
if __name__ == '__main__':
print("Logging config module")
When I was using this very same code on python2.7 i got this output:
22/05/2019 01:38:11 mainTest.py : INFO testing
On python 3.6 with the same code I got this error:
22/05/2019 03:17:59 mainRF.py : INFO testing
--- Logging error ---
Traceback (most recent call last):
File "/usr/lib/python3.6/logging/__init__.py", line 996, in emit
stream.write(msg)
TypeError: a bytes-like object is required, not 'str'
Call stack:
File "mainTest.py", line 126, in <module>
run_combinations()
File "mainTest.py", line 20, in run_combinations
log.info(message)
Message: 'testing'
Arguments: ()
When setting logging basic config I changed
python filemode='wb' to
python filemode='w' and it worked properly.
I'm trying to write my own little python flask app to monitor the hard drives of my server.
But since now, I'm getting trouble using the sqljobstore of apscheduler.
While the server is running, everything is fine. But after a restart, I can't access the web interface and getting the folowing output:
Unable to restore job "refresh_disks" -- removing it
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/apscheduler/util.py", line 289, in ref_to_obj
obj = getattr(obj, name)
AttributeError: module 'dirkules.tasks' has no attribute 'refresh_disks'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/apscheduler/jobstores/sqlalchemy.py", line 141, in _get_jobs
jobs.append(self._reconstitute_job(row.job_state))
File "/usr/local/lib/python3.6/dist-packages/apscheduler/jobstores/sqlalchemy.py", line 128, in _reconstitute_job
job.__setstate__(job_state)
File "/usr/local/lib/python3.6/dist-packages/apscheduler/job.py", line 272, in __setstate__
self.func = ref_to_obj(self.func_ref)
File "/usr/local/lib/python3.6/dist-packages/apscheduler/util.py", line 292, in ref_to_obj
raise LookupError('Error resolving reference %s: error looking up object' % ref)
LookupError: Error resolving reference dirkules.tasks:refresh_disks: error looking up object
[2019-04-26 15:46:39 +0200] [13296] [INFO] Shutting down: Master
Here is my config.py:
import os
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
#from apscheduler.jobstores.memory import MemoryJobStore
baseDir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(baseDir, 'dirkules.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
# The SCHEDULER_JOB_DEFAULTS configuration is per job, that means each job can execute at most 3 threads at the same time.
# The SCHEDULER_EXECUTORS is a global configuration, in this case, only 1 thread will be used for all the jobs.
# I believe the best way for you is to use max_workers: 1 when running locally
SCHEDULER_JOBSTORES = {'default': SQLAlchemyJobStore(url='sqlite:///' + os.path.join(baseDir, 'dirkules.db'))}
#SCHEDULER_JOBSTORES = {'default': MemoryJobStore()}
SCHEDULER_EXECUTORS = {'default': {'type': 'threadpool', 'max_workers': 3}}
SCHEDULER_JOB_DEFAULTS = {'coalesce': False, 'max_instances': 1}
SCHEDULER_API_ENABLED = True
init.py:
import dirkules.config as config
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_apscheduler import APScheduler
app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)
import dirkules.models
db.create_all()
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()
##app.before_first_request
from dirkules import tasks
# from dirkules.models import Time
# from sqlalchemy.orm.exc import NoResultFound
#
# try:
# Time.query.one()
# except NoResultFound:
# db.session.add(Time("Drives"))
# db.session.commit()
import dirkules.views
and tasks.py:
from dirkules import scheduler
import datetime
import dirkules.driveManagement.driveController as drico
#scheduler.task('interval', id='refresh_disks', seconds=10)
def refresh_disks():
#drives = drico.getAllDrives()
print("Drives refreshed")
Hopefully, you can help me!
Starting the scheduler as a side-effect of importing the module is considered bad practice and is also the likely reason why the attribute lookup fails. I would have to see a simplified, more complete example that reproduces the problem to be sure, however.
I have 3 python file in same directory.
b.py
class Something_b():
def b(self):
print("hello from b")
c.py
class Something_c():
def c(self):
print("hello from c")
a.py
from .b import *
from .c import *
Something_b.b()
Something_c.c()
but i am getting some errors like
Traceback (most recent call last):
File "F:/testing/test1/a.py", line 1, in <module>
from .b import *
ModuleNotFoundError: No module named '__main__.b'; '__main__' is not a package
it's fairly simple, just import the class from the file (you're importing all but you shouldn't put a period before the filename. The period before the filename is what's causing the error.)
in file b:
class hello:
def h(self):
print("Hello")
Then in file a:
from b import hello
hello.h('')
As you can see it printed hello, you can have as many files it doesn't really matter, when I'm doing a larger project I'll have a file for every key part of it. It makes it easier to read/find the function you are looking to edit.
try this:-
a.py
from b import *
from c import *
x = Something_b()
x.b()
y = Something_c()
y.c()
Note:- First receipt class constructor then call belonging methods from class