Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Correctly exiting an app
-
I have an app that runs in a while true loop. I want to exit the app correctly. How can I do this?
On a typical console app I'd use a "try ... except keyboardinterrupt" construct but this doesn't work in my app.
Any suggestions?
Regards
-
I am a beginner, but I will try to help
Not sure what you are looking for. To answer correctly I think you need to give more context of your app. But the below code prints something then exits first time through the loop. Not sure it helps or not. If not, I think better to rewrite your question and include some code.
import contacts import sys my_contacts = contacts.get_all_people() for person in my_contacts: print dir(person) sys.exit(0)
-
one option is to use ui, and show a button, which sets a global upon key press, which your while true loop checks for.
you can press the x button in the ui, which throws a keyboardinterrupt, but pythonista will not let you catch that exception.
-
The most readable way to end an infinite loop is to
break
out of the loop when some condition is met.# top_of_the_minute: loop forever until seconds is zero import datetime print('Waiting {}...'.format(datetime.datetime.now().second)) while True: # break out of the infinite loop when seconds is zero if not datetime.datetime.now().second: break # or exit('Done.') or quit('Done.') or raise SystemExit('Done.') or sys.exit('Done.') print('Done.')
I often use
sys.exit()
as mentioned by @Phukett2 above butraise SystemExit
orexit([text or number])
orquit([text or number])
work just as well and do not require an import.break
is best butraise SystemExit('Done.')
works well too.