I need to execute my second function cleanup after raise statement incase my else statement is executed in first function
but as this is an exception it doesn't work hence my second function which is cleanup() doesn't work .
Please note : I need to raise exception in my first function in case the string is not found
Please let me know what can I do to overcome this . Any help is very much appreciated
I have tried if else to achieve this with raise statement called in else but it doesn't works at all and I am stuck due to this . Please help
import os
import re
def validated():
if 'line is up , protocol is up' in open('C:/Users/diwak/Desktop/1.txt').read():
print("true")
else:
raise ("Not found")
def cleanup():
print ("cleanup still performed")
print (validated())
(cleanup())
My Expectation was both functions get executed :
1) Exception error raised for first function
2) Cleanup function executed
Actual output :
Program exits out of first function itself in case condition doesn't matches
I suppose this is desired (whereas it looks weird):
def validated():
try:
if 'helo' in 'hello world':
print("true")
else:
raise Exception("Not found")
except:
cleanup()
def cleanup():
print ("cleanup still performed")
validated()
def validated():
try:
if 'line is up , protocol is up' in open('C:/Users/diwak/Desktop/1.txt').read():
print("true")
else:
print("string not found")
raise Exception("Not found")
except:
pass
def cleanup():
print ("but cleanup still performed")
validated()
cleanup()
I think pass should also work if you agree
Related
I am trying to create an exception block that reads an error message and shuts down the program gracefully if my user inputs anything other than a number. How can I achieve this?
x=int(input("Choose a number:"))
try:
x==int()
except:
print("Invalid input.")
sys.exit()
y=int(input("Choose a number:"))
try:
y>=0 or y<=0
except:
print("Invalid input. Please try again.")
sys.exit()
In python the try block lets you test a block of code for errors.
The except block lets you handle the error.
In except block you can use ValueError as you are trying to convert the input to an integer, so if the input value is an integer, the code in the try block will be executed. otherwise the code in the excpet block will be executed.
You can use the while loop to exit the program only when you want by changing the value of the start variable to False.
start = True
while start:
try:
x=int(input("Choose a number for x :"))
y=int(input("Choose a number for y :"))
# if x > y:
# print("x is greater than y")
# elif x == y:
# print("x equal to y")
# else:
# print("x is less than y")
except ValueError:
print("Invalid input. Please enter a number")
start = False
Learn more about exceptions:
https://www.w3schools.com/python/python_try_except.asp
https://docs.python.org/3/tutorial/errors.html#handling-exceptions
Learn more about while loop:
https://www.w3schools.com/python/python_while_loops.asp
I am writing a code that has a class Fraction with attributes Numerator and Denominator. The Output should display the fraction in a simplified form. For e.g. 20/100 should be display as 1/5.
I have tried the below code but getting a Type Error as below:
TypeError: unsupported operand type(s) for /: 'int' and 'NoneType'
class fraction:
def get_data(self):
self.__num=int(input("Enter the Nr:"))
self.__deno=int(input("Enter the Dr:"))
if (self.__deno==0):
print("Fraction not possible")
exit()
def display_data(self):
self.__simplify()
print(self.__num,"/",self.__deno)
def __simplify(self):
print("The simplified fraction is")
common_divisor=self.__GCD(self.__num,self.__deno)
self.__num=(self.__num)/(common_divisor)
self.__deno=(self.__deno)/(common_divisor)
def __GCD(self,a,b):
if (b==0):
return a
else:
self.__GCD(b,a%b)
f=fraction()
f.get_data()
f.display_data()
I have no clue how to solve this Error. Please help me as i am new to Python and want to build strong basics.
The problem is in this function definition:
def __GCD(self,a,b):
if (b==0):
return a
else:
self.__GCD(b,a%b)
There's no return statement on the else clause. (Also, the else clause can be implicit instead of explicit.) Instead try:
def __GCD(self, a, b):
if b == 0:
return a
return self.__GCD(b, a % b)
I have written a code using if, try/except clause. I want to use "try" to check whether the parameters are correct and if those are correct the "print" function will run.
If the parameters are not right then the error message will be printed and the print section will not run.
The problem is when I am correct input it is running but when I am giving wrong input, after printing the error message I am getting NameError, saying "room1" is not defined. I understood why it is happening but I am confused how to get the correct output without getting an error.
My code is:
class Hotel:
def __init__(self,room,catagory):
if type(room) != int:
raise TypeError()
if type(catagory) != str:
raise TypeError()
self.room = room
self.catagory = catagory
self.catagories = {"A":"Elite","B":"Economy","C":"Regular"}
self.rooms = ["0","1","2","3","4","5"]
def getRoom(self):
return self.room
def getCatagory(self):
return self.catagories.get(self.catagory)
def __str__(self):
return "%s and %s"%(self.rooms[self.room],self.catagories.get(self.catagory))
try:
room1 = Hotel(a,"A")
except:
print("there's an error")
print (room1)
Your print should be in the try segment of your code as it will always execute whether there is an error or not.
class Hotel:
def __init__(self,room,catagory):
if type(room) != int:
raise TypeError()
if type(catagory) != str:
raise TypeError()
self.room = room
self.catagory = catagory
self.catagories = {"A":"Elite","B":"Economy","C":"Regular"}
self.rooms = ["0","1","2","3","4","5"]
def getRoom(self):
return self.room
def getCatagory(self):
return self.catagories.get(self.catagory)
def __str__(self):
return "%s and %s"%(self.rooms[self.room],self.catagories.get(self.catagory))
Initialization
try:
room1 = Hotel(a,"A")
print (room1)
except:
print("there's an error")
I'm trying to download the Flickr Style dataset using assemble_data.py provided in the examples folder. However, whenever I run this python crashes with error 'python quit unexpectedly'.
It seems to be related to multiprocessing and urllib. When I replace pool.map with a single threaded loop it works but is very slow. Also, if I run with multiprocessing but remove urlretrieve it seems to work too.
Answering my own question here... I resolved this by using urllib3 instead.
http = urllib3.PoolManager(10)
def download_image(args_tuple):
"For use with multiprocessing map. Returns filename on fail."
url, filename = args_tuple
try:
if not os.path.exists(filename):
print url + ' -> ' + filename
# Dont redirect.
response = http.request('GET', url, redirect=False)
with open(filename, 'wb') as f:
f.write(response.data)
with open(filename) as f:
assert hashlib.sha1(f.read()).hexdigest() != MISSING_IMAGE_SHA1
test_read_image = io.imread(filename)
return True
except KeyboardInterrupt:
raise Exception() # multiprocessing doesn't catch keyboard exceptions
except:
os.remove(filename)
return False
Gist here.
I have a function, that should do report, if test function success.
But, I don't want to do report, if there is an Exception inside test function.
I try to use pytest.fixture, pytest.yield_fixture, but all of them always call finalizers. How can I understand, that Exception had been raised in test function?
test.py StatisticClass: start
FStatisticClass: stop
finalizer
contest of test.py:
#pytest.mark.usefixtures("statistic_maker")
def test_dummy():
raise Exception()
content of conftest.py:
class StatisticClass():
def __init__(self, req):
self.req = req
pass
def start(self):
print "StatisticClass: start"
def stop(self):
print "StatisticClass: stop"
def if_not_exception(self):
"""
I don't want to call this if Exception inside yield.
Maybe, there is any info in request object?
"""
print "finalizer"
#pytest.yield_fixture(scope="function")
def statistic_maker(request):
ds = StatisticClass(request)
ds.start()
request.addfinalizer(ds.if_not_exception)
yield
ds.stop()
P.S. I can't use decorator because, I use fixture.