class Application(object):
def __init__(self, master):
self.master = master
Tk.report_callback_exception = self.show_error
def show_error(self, *args):
err = traceback.format_exception(*args)
messagebox.showerror('Title', f"{err[-1]}")
When an exception is raised I will have something like this:
If a create a simple Class Exception from Exception to easily pass description:
class Pingu_Exception(Exception):
pass
if i except a ZeroDivisionError and Raise my error(Pingu_Exception) from an imported python file
I can easily catch it
try:
x = 4 / 0
except ZeroDivisionError:
raise Pingu_Exception("Description")
The problem is when I try to catch imported Exception.
For example:
from requests.exceptions import ReadTimeout
class Woocommerce_api(object):
def __init__(self):
self.orders_endpoint = "orders/"
self.customers_endpoint = "customers/"
self.products_endpoint = "products/"
def __api_json(self, endpoint):
try:
wcapi = API(
url="https://www.xxxx.it",
consumer_key=self.consumer_key,
consumer_secret=self.consumer_secret,
wp_api=True,
version="wc/v1",
query_string_auth=True,
timeout=3
)
return wcapi
except requests.exceptions.ReadTimeout:
raise Pingu_Exception('"Timeout error\nIl server non risponde\nRiprova nuovamente')
This is what I catch:
but if a try to raise an requests.exceptions.ReadTimeout, in his same function, it will work:
def __api_json(self, endpoint):
try:
raise requests.exceptions.ReadTimeout
wcapi = API(
url="https://www.slow-sud.it",
consumer_key=self.consumer_key,
consumer_secret=self.consumer_secret,
wp_api=True,
version="wc/v1",
query_string_auth=True,
timeout=3
)
return wcapi
except requests.exceptions.ReadTimeout:
raise Pingu_Exception('"Timeout error\nIl server non risponde\nRiprova nuovamente')
return False
Related
I am creating a flask application and whenever I am trying to raise a UnicodeDecodeError from the class Validation and returning to my main try block then instead of going to UnicodeDecodeError exception it's going to Exception block
This is my main block from where I am calling my class Validation and expecting a UnicodeDecodeError
try:
validation = Validation(request.files['csvfile'])
validation.checkextension()
# columns = validation.check_columns(csv)
return redirect(request.url)
except UnicodeDecodeError:
# return Response("Error : %s"% UnicodeDecodeError)
return "Please enter a .csv extension"
except Exception as e:
print("abc",repr(e))
# return Response("Error : %s"% Exception)
return "Exception"
This is my class from where i am raising the error:
class Validation:
def __init__(self,file):
self.file = file
self.location = "./uploads/" + str(file.filename)
def checkextension(self):
try:
self.file.save(os.path.join("uploads", self.file.filename))
data = pd.read_csv(self.location)
except UnicodeDecodeError:
os.remove("./uploads/" + str(self.file.filename))
raise UnicodeDecodeError
except Exception:
print(Exception)
raise Exception
Also When I am printing the statement in except Exception as e:
I am getting this output:
TypeError('function takes exactly 5 arguments (0 given)')
I am getting TypeError but I am raising UnicodeDecodeError
Here is part of my code:
class KafkaProducer:
def __init__(self):
pass
bootstrap_server_host = system_config.get_kafka_bootstrap_server()
producer = Producer({'bootstrap.servers': bootstrap_server_host, "log.connection.close":False})
#classmethod
def send(cls, topic, key, value, data_type=None, uid=None):
try:
data = {"data": value, "createTime": long(time.time() * 1000)}
if data_type is not None:
data["type"] = int(data_type)
if uid is not None:
data["uid"] = long(uid)
cls.producer.produce(topic, json.dumps(data), key)
cls.producer.poll(0)
except BufferError as e:
logger.error('%% Local producer queue is full ' \
'(%d messages awaiting delivery): try again\n' %
len(cls.producer))
raise e
class new_application_scanner():
#classmethod
def scan_new_application(cls):
db_source = None
try:
db_source = DBConnector().connect()
db_cur = db_source.cursor()
...
KafkaProducer.send("RiskEvent", str(uid),
{"uid": uid, "country_id": user_info[1], "event_id": constant.RISK_EVENT_NEW_APPLICATION})
...
except Exception as e:
logger.error(traceback.format_exc())
finally:
if db_source is not None:
db_source.close()
def run_scan_new_application():
while is_scan_new_application_active:
try:
logging.info("scan_new_application starts at %s",time.time())
new_application_scanner.scan_new_application()
logging.info("scan_new_application ends at %s", time.time())
except Exception as e:
logging.error("new_application_scanner Error:%s",format(e))
logging.error(traceback.format_exc())
time.sleep(10)
t1 = threading.Thread(target=run_scan_new_application, name='run_scan_new_application', args=([]))
t1.start()
I have a kafka group of two servers. when I restart two servers one by one ,KafkaProducer.send() throws KafkaException(maybe some bug in confluent_kafka), and there are some exception logs.
The strange thing is the Exception continues to throw out of scan_new_application and there are exception logs in run_scan_new_application too. Even the thread stopped.Here is the exception logs:
2017-12-21 07:11:49 INFO pre_risk_control_flow.py:71 pid-16984 scan_new_application starts at 1513840309.6
2017-12-21 07:11:49 ERROR new_application_scan.py:165 pid-16984 Traceback (most recent call last):
File "/home/ubuntu/data/code/risk/Feature_Engine/data_retrive/pre_risk_control_flow/new_application_scan.py", line 163, in scan_new_application
{"uid": uid, "country_id": user_info[1], "event_id": constant.RISK_EVENT_NEW_APPLICATION})
File "/home/ubuntu/data/code/risk/Feature_Engine/data_retrive/kafka_client/Producer.py", line 27, in send
cls.producer.produce(topic, json.dumps(data), key)
KafkaException: KafkaError{code=_UNKNOWN_TOPIC,val=-188,str="Unable to produce message: Local: Unknown topic"}
2017-12-21 07:11:49 ERROR pre_risk_control_flow.py:75 pid-16984 new_application_scanner Error:KafkaError{code=_UNKNOWN_TOPIC,val=-188,str="Unable to produce message: Local: Unknown topic"}
The underlying client is raising KafkaException KafkaError{code=_UNKNOWN_TOPIC..} because it (now) knows the requested topic does not exist in the cluster (and auto topic creation is disabled). This is expected.
You are seeing the exception in run_scan_new_application because you are not catching KafkaException in send().
I am a decently new python coder and i wish to create a twitter bot in which everytime it retweets, it favourites the tweet as well. I am not exactly sure how to do that but when the bot searches, it sends out an error message of 'list index out of range'.
import tweepy, time, traceback
from tweepy.auth import OAuthHandler
from tweepy.streaming import StreamListener, Stream
ckey = ''
csecret = ''
atoken = ''
asecret = ''
auths = OAuthHandler(ckey, csecret)
auths.set_access_token(atoken, asecret)
api = tweepy.API(auths)
class listener(StreamListener):
def on_data(self, raw_data):
try:
tweet_text = raw_data.lower().split('"text":')[1].split('","source":"')[0].replace(",", "")
screen_name = raw_data.lower().split('"screen_name":"')[1].split('","location"')[0].replace(",", "")
tweet_cid = raw_data.split('"id:')[1].split('"id_str":')[0].replace(",", "")
#there is ment to be 4 spaces at tweet_text
accs = [''] # banned accounts screen name goes in here
words = ['hate' , 'derp' , 'racist' , 'evil' , 'keemstar' , 'mario' , 'kirby'] #banned words goes in here
if not any(acc in screen_name.lower() for acc in accs):
if not any(word in tweet_text.lower() for word in words):
fav(tweet_cid)
follow(screen_name)
retweet(tweet_cid)
tweet(myinput)
#call what u want to do here
#fav(tweet_cid)
#retweet(tweet_cid)
return True
except Exception as e:
print (str(e)) # prints the error message, if you dont want it to comment it out.
pass
def on_error(self, status_code):
try:
print( "error" + status_code)
except Exception as e:
print(str(e))
pass
def retweet(tweet_cid):
try:
api.retweet(tweet_cid)
time.sleep(random.randit(range(50,900)))
except Exception as e:
print(str(e))
pass
def follow(screen_name):
try:
api.create_friendship(screen_name)
time.sleep(random.randit(range(50,900)))
except Exception as e:
print(str(e))
pass
def fav(tweet_cid):
try:
api.create_favourite(tweet_cid)
time.sleep(random.randit(range(600,1100)))
except Exception as e:
print(str(e))
pass
def unfav(tweet_cid):
try:
api.destroy_tweet(tweet_cid)
time.sleep(random.randit(range(8000,9000)))
except Exception as e:
print(str(e))
pass
def tweet(myinput):
try:
api.update_status(myinput)
time.sleep(random.randit(range(1000,4000)))
except Exception as e:
print(str(e))
pass
# tags below
track_words = [""] #deleted all tags so easier to read
follow_acc = [] # all username converted to user ids
try:
twt = Stream(auths, listener())
twt.filter(track=track_words, follow = follow_acc)
except Exception as e:
print (str(e))
pass
Is this what you are asking for? It gives the stack trace of the exception.
import traceback
try:
s='hi'
s=s+1
except Exception as e:
print(traceback.format_exc())
Output:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
Hope this helps! :)
I'm having issues with my program just closing at random stages and am not sure why.
At first, I thought it was because it was getting an error but I added an error handle. still for some reason it just closes after say a few days of running and no error is displayed. code below
import requests
import lxml.html as lh
import sys
import time
from clint.textui import puts, colored
API_URL = "http://urgmsg.net/livenosaas/ajax/update.php"
class Scraper (object):
id_stamp = 0
def __init__(self, timeout, recent_messages=True):
self.timeout = timeout
self.handlers = []
self.recent_messages = recent_messages
def register_handler(self, handler):
self.handlers.append(handler)
return handler
def scrape(self):
try:
resp = requests.get(API_URL, params={'f': self.id_stamp}).json()
except requests.exceptions.ConnectionError as e:
puts("Error encountered when connecting to urgmsg: ", newline=False)
puts(colored.red(e.__class__.__name__), newline=False)
puts(" " + e.message)
return
if not resp['updated']:
return
old_id_stamp = self.id_stamp
self.id_stamp = resp['IDstamp']
# if old_id_stamp is 0, this is the first scrape
# which will return a whole bunch of recent past messages
if not self.recent_messages and old_id_stamp == 0: return
# Pager messages are returned newest to oldest, we want to
# process them oldest to newest
frags = lh.fragments_fromstring(resp['data'])[::-1]
for frag in frags:
msg = PagerMessage(frag)
for handler in self.handlers:
handler(msg)
def run(self):
while True:
self.scrape()
time.sleep(self.timeout)
class PagerMessage:
def __init__(self, fragment):
children = fragment.getchildren()
self.datetime = children[0].text
self.text = children[1].text
# channel starts with `- `
self.channel = children[1].getchildren()[0].text[2:]
self.response = 'CFSRES' in self.text
def __str__(self):
return "{} [{}]: {}".format(self.channel, self.datetime, self.text)
if __name__ == "__main__":
scraper = Scraper(5)
#scraper.register_handler
def handler(msg):
puts(colored.yellow(msg.channel), newline=False)
puts(" [", newline=False)
puts(colored.green(msg.datetime), newline=False)
puts("] ", newline=False)
if msg.response:
puts(colored.red(msg.text))
else:
puts(msg.text)
scraper.run()
Have I set this part out wrong ?
except requests.exceptions.ConnectionError as e:
puts("Error encountered when connecting to urgmsg: ", newline=False)
puts(colored.red(e.__class__.__name__), newline=False)
puts(" " + e.message)
return
As suggested by #sobolevn change
except: as e:
puts("Error encountered", newline=False)
puts(colored.red(e.__class__.__name__), newline=False)
puts(" " + e.message)
return
I am trying to implement a decorator to retry a urllib2.urlopen n times.
I cannot get the decorator to work. When I run it I get the followin error:
Traceback (most recent call last):
File "F:\retry\dec_class.py", line 60, in
x.getURLdata('127.0.0.1')
TypeError: 'NoneType' object is not callable
Can anyone give me hand please?
import serial, urllib2, time
from functools import wraps
import xml.etree.cElementTree as ET
from xml.etree.cElementTree import parse
class Retry(object):
default_exceptions = (Exception)
def __init__(self, tries, exceptions=None, delay=0):
self.tries = tries
if exceptions is None:
exceptions = Retry.default_exceptions
self.exceptions = exceptions
self.delay = delay
def __call__(self, f):
def fn(*args, **kwargs):
tried = 0
exception = None
while tried <= self.tries:
try:
return f(*args, **kwargs)
except self.exceptions, e:
print "Retry, exception: "+str(e)
time.sleep(self.delay)
tried += 1
exception = e
#if no success after tries, raise last exception
raise exception
return fn
class getURL(object):
#Retry(2 )
def getURLdata(self, IPaddress):
try:
f = urllib2.urlopen(''.join(['http://', IPaddress]))
f = ET.parse(f)
return f
except IOError, err:
print("L112 IOError is %s" %err)
except urllib2.URLError, err:
print("L114 urllib2.URLError is %s" %err)
except urllib2.HTTPError, err:
print("L116 urllib2.HTTPError is %s" %err)
except Exception, err :
print("L118 Exception is %s" %err)
x = getURL()
x.getURLdata('127.0.0.1')
Your __call__ method doesn't return fn. Instead, it implicitly returns None and so None is bound to getURLdata.