Terminating a Python Program - python

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

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

strange exceptions.SystemExit in Python 2.7

Here is my code and error message, anyone have any ideas why there are such exception? Thanks.
Source Code,
import sys
import tensorflow as tf
def main(argv):
print 'in main'
def f():
# this method will call def main(argv)
try:
tf.app.run()
except:
print "tf.app.run error ", sys.exc_info()
if __name__ == "__main__":
f()
Error Code,
in main
tf.app.run error (<type 'exceptions.SystemExit'>, SystemExit(), <traceback object at 0x10fa33f38>)
This is expected behavior: tf.app.run() passes the result of main() to sys.exit() (to make it easier to set an edit code), and sys.exit() raises an exceptions.SystemExit exception.
It's important to mention that using tf.app.run() is completely optional. Many TensorFlow scripts include it because it is more compatible with the Google Python coding style. However, if you need to customize the logic in your script, you are free to omit tf.app.run(). (The same applies to tf.app.flags.)
It's coming from the sys.exit() call, about which the following is said:
Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.
In your case, sys.exit seems to be called from the function run() unconditionally, so avoid intercepting SystemExit.
If you want to handle all kinds of application-relevant exception, try catching Exception instead of the bare except, since SystemExit:
...inherits from BaseException instead of Exception so that it is not accidentally caught by code that catches Exception. This allows the exception to properly propagate up and cause the interpreter to exit.

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

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

Is there a way to prevent a SystemExit exception raised from sys.exit() from being caught?

The docs say that calling sys.exit() raises a SystemExit exception which can be caught in outer levels. I have a situation in which I want to definitively and unquestionably exit from inside a test case, however the unittest module catches SystemExit and prevents the exit. This is normally great, but the specific situation I am trying to handle is one where our test framework has detected that it is configured to point to a non-test database. In this case I want to exit and prevent any further tests from being run. Of course since unittest traps the SystemExit and continues happily on it's way, it is thwarting me.
The only option I have thought of so far is using ctypes or something similar to call exit(3) directly but this seems like a pretty fugly hack for something that should be really simple.
You can call os._exit() to directly exit, without throwing an exception:
import os
os._exit(1)
This bypasses all of the python shutdown logic, such as the atexit module, and will not run through the exception handling logic that you're trying to avoid in this situation. The argument is the exit code that will be returned by the process.
As Jerub said, os._exit(1) is your answer. But, considering it bypasses all cleanup procedures, including finally: blocks, closing files, etc, it should really be avoided at all costs. So may I present a safer(-ish) way of using it?
If your problem is SystemExit being caught at outer levels (i.e., unittest), then be the outer level yourself! Wrap your main code in a try/except block, catch SystemExit, and call os._exit() there, and only there! This way you may call sys.exit normally anywhere in the code, let it bubble out to the top level, gracefully closing all files and running all cleanups, and then calling os._exit.
You can even choose which exits are the "emergency" ones. The code below is an example of such approach:
import sys, os
EMERGENCY = 255 # can be any number actually
try:
# wrap your whole code here ...
# ... some code
if x: sys.exit()
# ... some more code
if y: sys.exit(EMERGENCY) # use only for emergency exits
... # yes, this is valid python!
# Might instead wrap all code in a function
# It's a common pattern to exit with main's return value, if any
sys.exit(main())
except SystemExit as e:
if e.code != EMERGENCY:
raise # normal exit, let unittest catch it at the outer level
else:
os._exit(EMERGENCY) # try to stop *that*!
As for e.code that some readers were unaware of, it is documented, as well as the attributes of all built-in exceptions.
You can also use quit, see example below:
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
quit(0)
print('You typed ' + response + '.')

Categories