python - cmd module: capture Ctrl+C -


this question has answer here:

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

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -