can sys.exit() be made to exit bottle framework - python

I was hoping that putting 'sys.exit(1)' and catching it later like this will work.
xml_open()
try:
run(reloader=True, host='localhost', port=8080)
except SystemExit:
xml_save()
print "Exited ..."
Is there any other solution to exit these python micro-frameworks to exit from inside
the handlers ?

If its not being handled then check whether Its really executes sys.exist(1) statement,
because It may happen some other exception raised which is not being handled try this....
xml_open()
try:
run(reloader=True, host='localhost', port=8080)
except SystemExit:
xml_save()
print "Exited ..."
except Exception, e:
print "ohhh no.......",str(e)
import pdb
pdb.post_mortem()
sys.exit(-1)

In case this is still an issue for you, check my answer here for a clean solution of stopping the bottle framework.

From my limited experience, sys.exit() should work when reloader is turned off. Otherwise, reloader will reload the code on sys.exit() and your application will be resumed. Of course, I might be wrong about why sys.exit() doesn't work, but for me it worked when I turned off the reloader.

Related

How do you actually quit a python script?

None of these are kill -9 or anything close. What's the answer?
import sys
import os
try:
exit()
sys.exit()
os._exit()
quit()
except:
print("THIS SHOULD NOT RUN")
It's ridiculous of the Python language if any try-catch wrapping of an abort() or anything like it prevent's it from being able to die.
That's not something that exists in any other language that I know. abort() is an emergency safety measure.
Continuing from what already has been explained by #Mike Scotty:
Picking one: (sys.exit())
sys.exit() raises an exception, namely SystemExit. That's why you land in the except-block.
Example:
import sys
try:
sys.exit()
except:
print(sys.exc_info()[0])
OUTPUT:
<class 'SystemExit'>
In depth:
import sys
try:
sys.exit() # this always raises SystemExit
except SystemExit:
print("sys.exit() worked as expected")
except:
print("Something went horribly wrong") # some other exception got raised
OUTPUT:
sys.exit() worked as expected
Source
Try CTRL+C while in the script, should do the trick
Well, I don't like the way Python handles this but I've found a solution and it's actually kill -9:
Disclaimer: Unfortunately, you have to start and run the process as root.
os.system("sudo kill -9 " + str(os.getpid()))

Flask API - Auto Exit

i am making an Flask-API for my project and i want to achieve something when the server restarts or runs, meaning whenever the main block is executed i want to do a check.
the code:
if __name__ == '__main__':
try:
with open('x.p','rb') as pkl_PR:
ps=pickle.load(pkl_PR)
with open('y.p','rb') as pkl_df:
df=pickle.load(pkl_df)
with open('z.p','rb') as pkl_spl:
spl_df = pickle.load(pkl_spl)
except Exception as e:
logger.debug(e)
app.run(debug=True)
so if any one of the pickle file doesn't exist, i dont want to start the server and save a log file with error.
so how do i go about it?
You can call sys.exit() from inside the except block, that will cause your program to exit before starting the flask server.

custom output when control-c is used to exit python script

I would like the user to use control-c to close a script, but when control-c is pressed it shows the error and reason for close (which make sense). Is there a way to have my own custom output to the screen rather than what is shown? Not sure how to handle that specific error.
You could use try..except to catch KeyboardInterrupt:
import time
def main():
time.sleep(10)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('bye')
use the signal module to define a handler for the SIGINT signal:
import signal
import sys
def sigint_handler(signal_number, stack_frame):
print('caught SIGINT, exiting')
sys.exit(-1)
signal.signal(signal.SIGINT, sigint_handler)
raw_input('waiting...')
For general purpose code, handling the KeyboardInterrupt should suffice. For advanced code, such as threading, it is a whole different story. Here's a simple example.
http://docs.python.org/2/library/exceptions.html#exceptions.KeyboardInterrupt
try:
while 1:
x = raw_input("Type something or press CTRL+C to end: ")
print repr(x)
except KeyboardInterrupt:
print "\nWe're done here."

How to exit from Python without traceback?

I would like to know how to I exit from Python without having an traceback dump on the output.
I still want want to be able to return an error code but I do not want to display the traceback log.
I want to be able to exit using exit(number) without trace but in case of an Exception (not an exit) I want the trace.
You are presumably encountering an exception and the program is exiting because of this (with a traceback). The first thing to do therefore is to catch that exception, before exiting cleanly (maybe with a message, example given).
Try something like this in your main routine:
import sys, traceback
def main():
try:
do main program stuff here
....
except KeyboardInterrupt:
print "Shutdown requested...exiting"
except Exception:
traceback.print_exc(file=sys.stdout)
sys.exit(0)
if __name__ == "__main__":
main()
Perhaps you're trying to catch all exceptions and this is catching the SystemExit exception raised by sys.exit()?
import sys
try:
sys.exit(1) # Or something that calls sys.exit()
except SystemExit as e:
sys.exit(e)
except:
# Cleanup and reraise. This will print a backtrace.
# (Insert your cleanup code here.)
raise
In general, using except: without naming an exception is a bad idea. You'll catch all kinds of stuff you don't want to catch -- like SystemExit -- and it can also mask your own programming errors. My example above is silly, unless you're doing something in terms of cleanup. You could replace it with:
import sys
sys.exit(1) # Or something that calls sys.exit().
If you need to exit without raising SystemExit:
import os
os._exit(1)
I do this, in code that runs under unittest and calls fork(). Unittest gets when the forked process raises SystemExit. This is definitely a corner case!
import sys
sys.exit(1)
The following code will not raise an exception and will exit without a traceback:
import os
os._exit(1)
See this question and related answers for more details. Surprised why all other answers are so overcomplicated.
This also will not do proper cleanup, like calling cleanup handlers, flushing stdio buffers, etc. (thanks to pabouk for pointing this out)
something like import sys; sys.exit(0) ?
It's much better practise to avoid using sys.exit() and instead raise/handle exceptions to allow the program to finish cleanly. If you want to turn off traceback, simply use:
sys.trackbacklimit=0
You can set this at the top of your script to squash all traceback output, but I prefer to use it more sparingly, for example "known errors" where I want the output to be clean, e.g. in the file foo.py:
import sys
from subprocess import *
try:
check_call([ 'uptime', '--help' ])
except CalledProcessError:
sys.tracebacklimit=0
print "Process failed"
raise
print "This message should never follow an error."
If CalledProcessError is caught, the output will look like this:
[me#test01 dev]$ ./foo.py
usage: uptime [-V]
-V display version
Process failed
subprocess.CalledProcessError: Command '['uptime', '--help']' returned non-zero exit status 1
If any other error occurs, we still get the full traceback output.
I would do it this way:
import sys
def do_my_stuff():
pass
if __name__ == "__main__":
try:
do_my_stuff()
except SystemExit, e:
print(e)
Use the built-in python function quit() and that's it.
No need to import any library.
I'm using python 3.4
What about
import sys
....
....
....
sys.exit("I am getting the heck out of here!")
No traceback and somehow more explicit.
# Pygame Example
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('IBM Emulator')
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
fontObj = pygame.font.Font('freesansbold.ttf', 32)
textSurfaceObj = fontObj.render('IBM PC Emulator', True, GREEN,BLACK)
textRectObj = textSurfaceObj.get_rect()
textRectObj = (10, 10)
try:
while True: # main loop
DISPLAYSURF.fill(BLACK)
DISPLAYSURF.blit(textSurfaceObj, textRectObj)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
except SystemExit:
pass

Simple threading in Python 2.6 using thread.start_new_thread()

I'm following a tutorial on simple threading. They give this example and when I try to use it I'm getting unintelligible errors from the interpreter. Can you please tell me why this isn't working? I'm on WinXP SP3 w/ Python 2.6 current
import thread
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
thread.start_new_thread(myfunction,('MyStringHere',1))
except Exception as errtxt:
print errtxt
Executing this results in::
Unhandled exception in thread started by
Error in sys.excepthook:
Original exception was:
The information missing in the error is actually missing in the output.
The problem is that your main thread has quit before your new thread has time to finish. The solution is to wait at your main thread.
import thread, time
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
thread.start_new_thread(myfunction,('MyStringHere',1))
except Exception, errtxt:
print errtxt
time.sleep(5)
As a side note, you probably want to use the threading module. Your main thread will wait for all of those types of threads to be closed before exiting:
from threading import Thread
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
Thread(target=myfunction, args=('MyStringHere',1)).start()
except Exception, errtxt:
print errtxt
You need to wait until your Thread finishes its work, so you have to use Thread.join() :
from threading import Thread
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
t = Thread(None,myfunction,None,('MyStringHere',1))
t.start()
t.join()
except Exception as errtxt:
print errtxt
import thread
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
thread.start_new_thread(myfunction,('MyStringHere',1))
except Exception as errtxt:
print errtxt
while 1:
pass
Put while loop at last then it will work for you.
I tried it in Python 2.5 on a mac, after changing
except Exception as errtxt:
to
except Exception, errtxt:
The program did not throw an exception but also did not print anything. Not sure if that is helpful, but I do find it curious...
When I ran this code in Python 2.6 it worked, is it possible you have open threads already that are locked on the function? I recommend closing Python completely, checking your running processes to make sure nothing of yours is running and try again.

Categories