Python script problems - python

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

Related

How to make python not close it self after error, python exception

I have made an program in python that i converted into .exe using auto-py-to-exe and im wondering how to stop .exe stop closing it self after an error (python exception) the .exe closes it self in the speed of light and you cant read the error.
Does someone knows how to make it not close it self?
using input doesnt work if the exception happens in a pip library
Thanks
You can use a try-except based system (that you have to build suitably to catch every exception of your code) and to print the exception you can use the module traceback like so:
try:
## code with error ##
except Exception:
print("Exception in user code:")
print("-"*60)
traceback.print_exc(file=sys.stdout)
print("-"*60)
or you could use a simpler form like:
try:
## code with error ##
except Exception as e:
print(e, file='crash log.txt')
that only prints the error class (like file not found).
I should also point out that the finally keyword exists with the purpose of executing code either if an exception arose or not:
try:
## code with error ##
except: #optional
## code to execute in case of exception ##
finally:
## code executed either way ##
Something you could do on top of that is logging everything your program does with
print(status_of_program, file=open('log.txt','a'))
this is useful to see exactly at what point the program has crashed and in general to see the program in action step by step.
But a thing you should do is properly test the program while in .py form and if it works you could possibly assume the error comes from the actual exportation method and consult the documentation or try exporting simpler programs to catch the difference (and so the error).
i'd suggest to consult:
https://docs.python.org/3/library/exceptions.html
to learn the error types and the try-except construct.
If input() doesn't work try using sys.stdout().
I gather that this is a console app. If it's a GUI app, you can use a similar approach but the details will be different.
The approach I'd use is to set sys.excepthook to be your own function that prints the exception, then waits for input. You can call the existing exception hook to actually do the printing.
import sys, traceback as tb
oldhook = sys.excepthook
def waitexcepthook(type, exception, traceback):
oldhook(type, exception, traceback)
input()
sys.excepthook = waitexcepthook

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 it possible to create never crashing python code with exception handling?

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.

Display message on crash in Python?

I am [relatively] new to python, and I'm making an application that calculates compound interest. I want users to be able to report their crashes, and to do this I need to write some code that executes when there is a problem and the program stops running. I just want to display some text and show the contents of some variables so the user can cut and paste them into an email.
Is this feasible?
Thanks!
If you know something that will throw an error, use a try except finally block.
try:
raise ANonSenseError()
except ANonSenseError:
# Log it
# Bring some dialog for users to report it.
finally:
# Well, this part is optional, but you can use it in case an exception isn't thrown
# It will always run
If you don't want to use the try except block, you could try and establish something that will have to execute if the program stops. You might not be able to find out what error it is, but you will have the flexibility of doing anything freely after the main section of your program crashes.
Also, a suggestion if you're using Tkinter: use Tkinter.Toplevel to raise a top level window.
Take a look at this question, which should give you some guidance about raising a new window when your main application crashes.
Sure take a look at how to use try/except here: https://docs.python.org/3.4/tutorial/errors.html
Example:
#!/usr/bin/env python3
import sys
def calculation():
return 1/0
if __name__ == "__main__":
try:
print(calculation())
except Exception as e:
print("Oops, something went wrong: {}".format(e), file=sys.stderr)
sys.exit(1)
Use the traceback module to handle you stacktrace. I use this under most of my exceptions
import traceback
import sys, os
try:
bla
except Exception as e:
top = traceback.extract_tb(sys.exc_info()[2])[-1]
print '{} : {} in {} at line {}'.format(type(e).__name__, str(e), os.path.basename(top[0]), str(top[1]))
Output:
NameError : name 'bla' is not defined in test.py at line 4

Terminating a Python Program

What command do you use in python to terminate a program?
i.e. the equivalent of "end" in basic, or "quit" in BASH.
I see that "break" takes you out of a loop, and "quit" is all tied up with "class" stuff that I do not comprehend yet.
i tried
import sys
sys.exit()
but it will display following error :
Traceback (most recent call last):
File "C:\Documents and Settings\....\Desktop\current file_hand\Python_1.py", line 131, in <module>
sys.exit()
SystemExit
is there any solution for it .
sys.exit(error_code)
Error_code will be 0 for a normal exit, 1 or some other positive number for an exit due to an error of some kind, e.g. the user has entered the wrong parameters.
sys.exit() "is undefined on some architectures", (although it worked when I tried it on my Linux box!)
The official python docs explains this more fully.
It's an extremely good idea for all your programs and scripts to follow the return code convention; 0 for OK, something else for error, (normally 1)
For example, if you run a script which grabs some data out of a database; returning 0 and no output, means the database is perfectly fine there's just nothing in it (or nothing matching your query). returning 1 and no output means there is a fault with the database, the whole process should abort, because to continue would corrupt the other system too.
sys.exit() raises the SystemExit exception.
If you don't catch that exception the program ends.
Since you're getting that output, I'm not sure what is happening, but I guess that you're catching all exceptions and printing them yourself:
try:
...
except:
print exception somehow
raise
If that's the case, don't do that. catch Exception instead:
...
except Exception:
...
That way you won't catch things not meant to be catched (like SystemExit).
You should also consider alternatives to exiting directly. Often return works just as well if you wrap code in a function. (Better, in fact, because it avoids sys.exit() weirdness.)
def main():
...do something...
if something:
return # <----- return takes the place of exit
...do something else...
main()
sys.exit() #to exit the program
return #to exit from a function
import sys
sys.exit(0)
Try running a python interpreter out of your IDE. In my Windows installation the simple command line python.exe, both options work:
>>> import sys
>>> sys.exit()
or
>>> raise SystemExit
In your case, your error is likely that you have a bare except block that is catching the SystemExit exception, like this:
import sys
try:
sys.exit(return_code)
except:
pass
The correct way to fix your problem is to remove the except: portion, and instead just catch the Exceptions you expect to be possibly raised. For example:
try:
# Code which could raise exceptions
except (NameError, ValueError):
# Do something in case of NameError or ValueError, but
# ignore other exceptions (like SystemExit)
However, if you really wanted your program to exit, the following code will work:
import os
try:
os._exit(return_code)
except:
pass
This will exit even with the except: clause, as it just directly calls the C function of the same name which kills your process. This is not recommended unless you know what you are doing, since this will not call cleanup handlers or flush open IO buffers.
I met this problem on Windows where I needed to close ParaView (I could not use pvbatch or pvpython, because of OpenGL initialization, and sys.exit does not work)
Below is the specific solution for Windows.
# import os module
import os
# delete given process
os.system('wmic process where name="Process_Name" delete')
# for example
os.system('wmic process where name="paraview.exe" delete')
Source of this solution is here

Categories