How can I have a python script safely exit itself? - python

Heres the scenario I have a password that must be entered if entered wrong the script will not proceed and just exit itself? But how can I tell the script to safely exit itself?
I tried sys.exit() but that gives a traceback error and doesn't seem like a very clean exit method.

In fact, sys.exit() will only throw a SystemExit exception, which would make the program exit if this exception wasn't catched, but I don't think it's poor coding.
Anyway, another possibility is to use os._exit(0) if you need to exit immediately at any cost. (cf. http://docs.python.org/2/library/exceptions.html#exceptions.SystemExit)

you are using the sys module, but you haven't imported it.
add this before the sys.exit() line :
import sys

Related

Exit shell script from python

I Have a shell script which in turn runs a python script, I have to exit from the main shell script when an exception is caught in python. Can anyone suggest a way on how to achieve it.
In Python you can set the return value using sys.exit(). Typically when execution completed successfully you return 0, and if not then some non-zero number.
So something like this in your Python will work:
import sys
try:
....
except:
sys.exit(1)
And then, as others have said, you need to make sure your bash script catches the error by either checking the return value explicitly (using e.g. $?) or using set -e.

Catching Keyboard Interrupt with Raw Input

I have a bit of python code to to try and make raw_input catch keyboard interrupts. If I run the code in this function it works perfectly fine. But if I run it in my program, the print statement is never made, indicating that the keyboard interrupt is not caught. The program attempts to exit and fails until it escalates to SIGKILL, which of course works fine. My guess is somewhere else the keyboard interrupt is being caught, preventing the exception from running at all. My question is, where would such an interrupt likely occur, and how can I prevent it from blocking this one. My plan has been to add a slight delay between the program catching a keyboard interrupt and killing itself to give excepting here a moment to catch.
Any ideas appreciated
Thanks!
import sys
def interruptable_input(text=''):
'''Takes raw input, but accepts keyboard interrupt'''
try:
return raw_input(text)
except KeyboardInterrupt:
print "Interrupted by user"
sys.exit()
I have narrowed it down to the following:
import sys
text=''
try:
print raw_input(text)
except KeyboardInterrupt:
print "Interrupted by user"
sys.exit()
Which works perfectly when i run it on the command line using python 2.7.
It lets me type an input on the console and when I hit ctrl+c it prints intterupted by user
Edit:
I misread your question at first, however when i use the method from your example and call it from another method the result is the same
I have determined the reason for my issue was another interrupt handler killing the script before the KeyboardInterrupt was hit. I solved it by setting my own interrupt handler for signal.SIGINT like so:
import sys
import signal
signal.signal(signal.SIGINT, signal_term_handler)
def signal_term_handler(signal, frame):
'''Handles KeyboardInterrupts to ensure smooth exit'''
rospy.logerr('User Keyboard interrupt')
sys.exit(0)
it's slightly less direct but it get's the job done. Now raw_input() will simply die when told to.

Terminate Blender with Exit Code "1" when run from command line

I am working with an automated Blender python script and I would like to know how to terminate it with an Exit Code 1 when an Exception occurs.
The problem seems to be that the exit code from blender is always 0 even if the python script fails.
The following script definately produces a non-zero exit code, but blender sets exit code to 0
def main():
raise Exception("Fail")
sys.exit(1)
I also tried the --python-exit-code command line argument but to no effect:
C:\blender.exe --python-exit-code 2 --disable-abort-handler -P bake.py
this gives a slightly better result, because I get the following message:
Error: script failed, file: 'bake.py', exiting with code 2.
Unfortunately the exit code is still 0.
Can anyone enlighten me with some explanations or solutions on how I can exit the process with the correct exit code?
Thanks a lot for any hints!
--python-exit-code as stated in the documentation sets the exit code if the command line script called with --python raises an exception, not when it exits with a non-zero code.
Set the exit-code in [0..255] to exit if a Python exception is raised (only for scripts executed from the command line), zero disables.
Thus the only solution is to do your checking, and raise an exception manually, then catch it and exit in the except block. (If you don't exit right away, the exit code reverts to 0.
This code worked for me when doing unit tests inside a blender addon.
import unittest
from tests.my_test import MyTest
import sys
def run():
suite = unittest.defaultTestLoader.loadTestsFromTestCase(MyTest)
success = unittest.TextTestRunner().run(suite).wasSuccessful()
if not success:
raise Exception('Tests Failed')
try:
run()
except Exception:
sys.exit(1)

Python run system command and then exit... won't exit

I have the following python code:
os.system("C:/Python27/python.exe C:/GUI/TestGUI.py")
sys.exit(0)
It runs the command fine, and a window pops up. However, it doesn't exit the first script. It just stays there, and I eventually have to force kill the process. No errors are produced. What's going on?
instead of os.system use subprocess.Popen
this runs a command and doesn't wait for it and then exits:
import subprocess
import sys
subprocess.Popen(["mupdf", "/home/dan/Desktop/Sieve-JFP.pdf"])
sys.exit(0)
note that os.system(command) like:
p = subprocess.Popen(command)
p.wait()
KeyboardInterrupts and signals are only seen by the process (ie the main thread). If your nested command hangs due to some kind of file read or write block, you won't be able to quit the program using any keyboard commands.
Why does a read-only open of a named pipe block?
If you can't eliminate the source of the disk block, then one way is to wrap the process in the thread so you can force kill it. But if you do this, you leave opportunity for half-written and corrupted files on disk.
I suggest using os._exit instead of sys.exit, as sys.exit doesnt quit a program but raises exception level, or exits a thread. os._exit(-1) quits the entire program
import sys ,subprocess
subprocess.Popen(["C:/Python27/python.exe", "C:/GUI/TestGUI.py"])
sys.exit(0)
Popen from subprocess module what you are looking for.

How do I abort the execution of a Python script? [duplicate]

This question already has answers here:
How do I terminate a script?
(14 answers)
Closed 3 years ago.
I have a simple Python script that I want to stop executing if a condition is met.
For example:
done = True
if done:
# quit/stop/exit
else:
# do other stuff
Essentially, I am looking for something that behaves equivalently to the 'return' keyword in the body of a function which allows the flow of the code to exit the function and not execute the remaining code.
To exit a script you can use,
import sys
sys.exit()
You can also provide an exit status value, usually an integer.
import sys
sys.exit(0)
Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero.
import sys
sys.exit("aa! errors!")
Prints "aa! errors!" and exits with a status code of 1.
There is also an _exit() function in the os module. The sys.exit() function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os._exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used.
The Python docs indicate that os._exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances.
You could put the body of your script into a function and then you could return from that function.
def main():
done = True
if done:
return
# quit/stop/exit
else:
# do other stuff
if __name__ == "__main__":
#Run as main program
main()
import sys
sys.exit()
You can either use:
import sys
sys.exit(...)
or:
raise SystemExit(...)
The optional parameter can be an exit code or an error message. Both methods are identical. I used to prefer sys.exit, but I've lately switched to raising SystemExit, because it seems to stand out better among the rest of the code (due to the raise keyword).
Try
sys.exit("message")
It is like the perl
die("message")
if this is what you are looking for. It terminates the execution of the script even it is called from an imported module / def /function
exit() should do the trick
exit() should do it.
If the entire program should stop use sys.exit() otherwise just use an empty return.

Categories