How to exit a running python program at a python prompt?

I wrote a realistic game of life. I set up two modes, one is automatic and the other is manual, which I mean is a way to display the result of the game. For automatic mode, I cannot stop a running run without ctrl + q or ctrl + c (which displays an error message). So, is there a way that allows me to stop the running program and return to the python >>> prompt by pressing the key defined by me, say ctrl + k . Thanks.

+4
source share
3 answers

You cannot use arbitrary keystrokes, but to handle a regular interrupt (e.g. control-C) without errors, all you need to do is catch the KeyboardInterrupt exception that it throws, i.e. just wrap your entire loop code with

 try: functionthatloopsalot() except KeyboardInterrupt: """user wants control back""" 

To โ€œget control backโ€ in an interactive prompt, the script must work with -i (for โ€œinteractiveโ€) or use more complex interactive Python shells such as ipython.

+3
source

If you can intercept the event raised by the key, press and call a specific function, than you could do this:

 def prompt(): import code code.interact(local=locals()) 

or if you are using IPython:

 def prompt(): from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed() ipshell(local_ns=locals()) 

This will open a python or IPython shell in which you can access the current environment.

Greetings Andrea

+1
source

Do you run it from an iterative query and just want to return to the prompt. Or do you start it from the shell and want to get a python prompt, but with the current state of program execution?

For a later version, you could rule out keyboard hijacking in your code and break into the python debugger (pdb).

  import pdb
 try:
     mainProgramLoop ()
 except (KeyboardInterrupt, SystemExit):
     pdb.set_trace ()
+1
source

All Articles