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.
Related
Hi can anyone help me set up a task . I want to automate a task to open an app at a specific time but for now i'm just trying to open an app with my code but when i try to run it in vscode i have to type the file name into the terminal for it to open .
def openFile():
try:
os.startfile(r"C:\Users\user\Documents>hi.txt")
except Exception as e:
print(str(e))
The problem was that it was running too fast
I added a time function and it's running perfectly now
while os.startfile(r"C:\Users\user\Documents\hi.txt"):
print("I'm going to wait 5 seconds now!")
time.sleep(5)
Have written GCP Cloud Function in Python 3.7. While executing, sys.exit() I'm getting 'A server error occurred ...'. I need to exit out of the function and have written following code.
import sys
if str(strEnabled) == 'True':
printOperation = "Operation: Enabling of user"
else:
sys.exit() #Exit From the Program
Please suggest, what I'm missing here.
Use return instead of sys.exit
Copied from bigbounty's comment
If you are calling a function from another function and needs to directly exit from the inner function without return you can use abort.
abort will directly return the response and exit the program from the place you are calling it.
import sys
from flask import abort
if str(strEnabled) == 'True':
printOperation = "Operation: Enabling of user"
else:
# abort(200) #return 200
abort(500, description="Exit") #return 500
Note: cloud functions use flask module internally, so you need not
install it separately.
I am having a main program which is defined like this:
main.py
def main():
try:
registry.start_server()
except:
print("Shutting down the program")
pass
if __name__ == '__main__':
main()
registry.start_server() is the method in another module which looks like this:
def start_server():
t_server = threading.Thread(target=server.start)
t_server.start()
try:
t_server.join()
except KeyboardInterrupt:
print("Error")
raise ValueError
finally:
fp.close()
server.start is the method in another module which does some listening work in a while(True) manner. I am not sure how to stop the whole program when clicking Stop in PyCharm which is Ctrl + C (Signal). I tried with Event but without success. I get to the main.py by raising an exception when the signal gets caught but that does not terminate the whole program. It shows Waiting for program to detach. The only way is to use SIGKILL. I don't understand where does the program keeps hanging? I have also tried calling sys.exit(0) when the signal gets caught and creating the thread as Deamon but that didnt help either.
EDIT
While True method in another module
def start(self, event):
try:
while True:
if event.is_set():
if self.pubsub.channels:
print("It enters here")
message = self.pubsub.get_message(True)
if message:
.
.
.
else:
return
To solve the problem, all you need to do is:
let the child-thread exit, and
let main thread join the child-thread.
I've been messing around with a Django project.
What I want to achieve is the Django project starting up in another process while the parent process initiates a load of arbitary code I have written (the backend of my project). Obviously, the Django process and parent processes communicate. I'd like a dictionary to be read and written to by the processes.
I have the following code, based upon examples from here:
#!/usr/bin/env python
from multiprocessing import Process, Manager
import os
import time
from dj import manage
def django(d, l):
print "starting django"
d[1] = '1'
d['2'] = 2
d[0.25] = None
l.reverse()
manage.start()
def stop(d, l):
print "stopping"
print d
print l
if (__name__ == '__main__'):
os.system('clear')
print "starting backend..."
time.sleep(1)
print "backend start complete."
manager = Manager()
d = manager.dict()
l = manager.list(range(10))
p = Process(target=django, args=(d, l))
p.start()
try:
p.join()
except KeyboardInterrupt:
print "interrupt detected"
stop(d, l)
When I hit CTRL+C to kill the Django process, I'm seeing the Django server shut down, and stop() being called. Then what I want to see is the dictionary, d, and list, l, being printed.
Output is:
starting backend...
backend start complete.
starting django
Validating models...
0 errors found
Django version 1.3, using settings 'dj.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
^Cinterrupt detected
stopping
<DictProxy object, typeid 'dict' at 0x141ae10; '__str__()' failed>
<ListProxy object, typeid 'list' at 0x1425090; '__str__()' failed>
It can't find the dictionary or list after the CTRL+C event. Has the Manager process been terminated when the SIGINT is issued? If it is, is there anyway to stop it from terminating there and terminating with the main process?
I hope this makes sense.
Any help greatly receieved.
Ok, as far I see no possibility to simply ignore exception. When you rise one, you always go straight into a "except" block if there is one. What I'm proposing here is something what will restart your django application on each ^C, but note, that there should be added some back door for leaving.
In theory, you can wrap each line with a try..except.. block and that would act like a restart of each line, what will not be as visible as restart of whole script. If anyone finds a really-working solution, I will be the first one to upvote him.
You can set all inside your if (__name__ == '__main__'): into o main function and leave something like this:
def main():
#all the code...
if (__name__ == '__main__'):
while True:
try:
main()
except KeyboardInterrupt:
pass
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.