Is it possible to create never crashing python code with exception handling? - python

I wonder if the below python code (specifically http server) ever crashes? Assuming that there is no grammer error in any of the library code(already compiled), what I think that handling the exceptions in a while loop should be sufficient for this code not to crash anytime. I tried the below code for a while and never crashed, but I wonder if theoretically or practically possible for this program to crash?
while True:
try:
server = HTTPServer(('', PORT_NUMBER), myHandler)
server.serve_forever()
except:
try:
server.socket.close()
except:
pass
The actual reason I am asking this question that I don't want to deal with UNIX staff to watch the process and restart it if it crashes. Is the above solution sufficient?
Thanks.

If "except" block has worng code, it can crash cause of it. I mean, something like that:
# path/to/py3
FOO = [1,2,3]
try:
# index out of bound, try block has error, so it goes ahead and executes except-block
print(FOO[4])
except:
# if there is some kind of error, like Syntax error, program can crash
print "Index out of bound!"
print("2"+2)
print(FOO["BAR"])
but if exception block has the correct logic too, then programm should work without crashing

Like Klaus D. already mentioned in his comment, there can be cases where the socket close code in your except block crashes. You could optionally also throw a try except around that as well...
Another option is to use something like this (no UNIX involved):
http://supervisord.org/
It's easy to run and will automatically restart your program if it crashes.

Related

Unable to KeyboardInterrupt while loop

I have a python script that runs on an infinite loops. In the loop multiprocess and async functions happen so normally I catch KeyboardInterrupt to properly kill all the processes.
Using similar code somehow on one of the loops I am unable to catch the KeyboardInterrupt the loop just keeps going.
logic goes like that:
try:
while True:
do stuff
except (KeyboardInterrupt, SystemExit):
exit cleanly
Normally I would suspect a blanket try ... except somewhere in the children functions but I went over the whole code base and while there is a lot of error catching everything is specific.
Is there a way to trace errors and somehow figure out where the KeyboardInterrupt is caught ?
Thank you
****** Edit after some debugging...
So I disabled the code part by part until I cornered the bug:
Somewhere in the code I was calling a method that was missing self and was not marked as #staticmethod.
Changing that fixed my issue.
This works for me.
try:
while True:
print(1)
except KeyboardInterrupt:
raise
EDIT:
Actually read your question, I won't be able to tell you why it's not raising an error without seeing the rest or more of the code.

Is there anything in Python like a try-finally except it still raises exceptions normally?

Suppose I want to run some function in Python, ensuring that whether it fails or not some cleanup code is always run. Something like this:
try: some_function()
finally: cleanup()
Ok, simple enough. But hold up! If any exceptions occur in the try block, they'll be suppressed. So really this construct did more than I wanted. All I really wanted to do was make sure some cleanup code runs after the function whether it finishes successfully or not. I still want any exceptions which occur in my function to happen normally. Perhaps that would look something like this:
do: some_function()
finally: cleanup()
Of course, that isn't real Python code. The actual way which I've found to do this is like follows:
try: some_function()
except Exception as error: raise error
finally: cleanup()
Eww, gross. I'm adding an extra line to re-throw an exception which I wanted to just happen normally in the first place. And additionally the stack trace now has an extra line in it showing the except Exception as error: raise error bit. This seems less than ideal to me, but it also seems to be the only way to accomplish what I'm trying to do.
So is this really the way I'm supposed to go about this?
If yes, then I have a further question: Why doesn't Python have a dedicated construct for simply ensuring some block of code runs whether some other block succeeds or not?
As far as my small mind is concerned, this whole idea has little to do with exception handling, since I don't actually want to keep exceptions from occurring where they normally would in the stack trace. Therefore, forcing people to use a try-except-finally construct seems just weird to me.
Python does!
try:
1/0
finally:
print("Hello, world!")
print("This will not print.")
Alright so as #user2357112 pointed out it looks like I somehow had the wild misconception that the try part of a try-except-finally construct is what catches exceptions. If anyone else gets confused similarly... it's the except bit that does the catching. Pretty obvious after some thinking, but hey everyone has brain farts sometimes.

Do 'while' loops work with try and except?

So I have a script that isn't quite working yet but I am hoping to get it to a point where it keeps trying to connect to a server until it finally succeeds (using the paramiko library). In simplistic terms, this is what my code is like:
canConnect = False
while canConnect == False:
try:
stdin, stdout, stderr = ssh.exec_command('ps')
if stdout.read():
canConnect = True
else:
# cannot connect
time.sleep(20)
except:
# cannot connect
time.sleep(20)
Now... this would be quite basic for a simple if statement but gets more complicated because I need to use "try" and "except". If the code can connect successfully (using "ps" as a random command that returns content and will prove the server is connectable), I assume it passes into the if condition that then sets canConnect to True and stops the loop. If it cannot connect, I think Paramiko will throw an exception (I put the "else" command there just in case), but once it hits the "except", it should wait for 20 seconds and then I assume the while statement will take the code back to the beginning and start again? What I have witnessed so far is that some kind of loop is happening, but it doesn't actually appear to be attempting to connect to the server.
Also, an unrelated question, documentation is scarce but I assume Paramiko /has/ to take 3 arguments like that to perform an exec_command (regardless of variables assigned, they will take standard output In, Out, Err in that order?)? I also assume it is uncommon to assign multiple comma-delimited variables to something like that, besides lists or method calls?
I think your use of except: may be masking the real problem, as it catches all exceptions, and disregards them. That would explain the some kind of loop is happening, but it doesn't actually appear to be attempting to connect to the server behavior. consider changing that to something like:
except (paramiko.SSHException, socket.error)

Python, how to keep program going after exception is caught

probably a simple question as I fairly new to python and programming in general but I am currently working on improving a program of mine and can't figure out how to keep the program going if an exception is caught. Maybe I am looking at it the wrong way but for example I have something along these lines:
self.thread = threading.Thread(target=self.run)
self.thread.setDaemon(True)
self.thread.start()
def run(self):
logging.info("Starting Awesome Program")
try:
while 1:
awesome_program(self)
except:
logging.exception('Got exception on main handler')
OnError(self)
def OnError(self):
self.Destroy()
Obviously I am currently just killing the program when an error is reached. awesome_program is basically using pyodbc to connect and run queries on a remote database. The problem arises when connection is lost. If I don't catch the exceptions the program just freezes so I set it up as it is above which kills the program but this is not always ideal if no one is around to manually restart it. Is there an easy way to either keep the program running or restert it. Feel free to berate me for incorrect syntax or poor programming skills. I am trying to teach myself and am still very much a novice and there is plenty I don't understand or am probably not doing correctly. I can post more of the code if needed. I wasn't sure how much to post without being overwhelming.
Catch the exception within the loop, and continue, even if an exception is caught.
def run(self):
logging.info("Starting Awesome Program")
while 1:
try:
awesome_program(self)
except:
logging.exception('Got exception on main handler')
OnError(self)
BTW:
Your indentation seems messed up.
I'd prefer while True. Python has bool type, unlike C, so when a bool is expected - give while a bool.
You're looking for this:
def run(self):
while True:
try:
do_things()
except Exception as ex:
logging.info("Caught exception {}".format(ex))
Take a look at Python Exception Handling, and in particular Try...Except. It will allow you to catch particular errors and handle them however you choose fit, even ignore them completely, if possible. For example:
try:
while something == True:
do_stuff()
except ExceptionType:
print "Something bad happened!" #An error occurred, but the script continues
except:
print "Something worse happened!"
raise #a worse error occurred, now we kill it
do_more_stuff()

Python script problems

So this is a script that I am coding for my buddies companies customer support. Basically, what it does is call using the IP phones that are in the script, it works, but with problems. Here is the code:
import urllib, urllib2, sys
num = sys.argv[1]
print 'Calling'
phones = [
'http://phone1/index.htm',
'http://phone2/index.htm',
'https://phone3/index.htm',
'https://phone4/index.htm',
'https://phone5/index.htm'
]
data = urllib.urlencode({"NUMBER":num, "DIAL":"Dial", "active_line":1})
while 1:
for phone in phones:
try:
urllib2.urlopen(phone,data) # make call
urllib2.urlopen(phone+"?dialeddel=0") # clear logs
except: pass
The first problem is that it only calls using phone one... Right now it is setup to keep calling over and over, for debugging purposes, and I seem to only be getting calls from phone one... The second problem is that the script will not terminate. ctrl+c does not work... The only way to terminate it (that I know of) is to end the ssh session. Now, I am new to python so both of these are probably just stupid mistakes so hopefully someone can help. Thanks!
Try replacing the try catch block like this,
try:
<code>
except Exception as exp:
<code>
While using the below code.
except:
pass
The system will catch SystemExit, KeyboardInterrupt and other things that you probably don't want to catch.
Thanks.
Your try block may be catching the Ctrl-C. Try modifying it so you only catch the specific exceptions you expect. See KeyboardInterrupt for more about Ctrl-C as an exception.
Replace:
try:
urllib2.urlopen(phone,data) # make call
urllib2.urlopen(phone+"?dialeddel=0") # clear logs
except: pass
with:
urllib2.urlopen(phone,data) # make call
urllib2.urlopen(phone+"?dialeddel=0") # clear logs
so you can see traceback and find the error

Categories