python - cmd module: capture Ctrl+C -
this question has answer here:
- how capture sigint in python? 9 answers
i using python's default cmd module create command-line-based app.
according docs ctrl+d (which signals eof command line) can captured implementing function called do_eof, works pretty well.
however, there way capture ctrl+c well? want execute specific function (which saves unsaved changes) before terminating python-script, main motivation doing this.
currently, capture keyboardinterrupts using try-except-block following:
if __name__ == '__main__': try: mycmd().cmdloop() except keyboardinterrupt: print('\n') i tried extend into:
if __name__ == '__main__': try: app = mycmd().cmdloop() except keyboardinterrupt: app.execute_before_quit() print('\n') which leads following nameerror:
name 'app' not defined how can capture ctrl+c?
i think signal somehow trick, not sure...
remark: script needs running on both unix- , windows-based systems.
ctrl c activates system exit exception, i'm pretty sure can catch try , except. note: catch systemexit must specify in except explicitly.
Comments
Post a Comment