简体   繁体   中英

How to quit the running python program to python prompt?

I wrote a implementation of conway's game of life. I set up two modes, one is auto and the other is manual, which I mean the way to ouput the result of the game. For the auto mode, I cannot stop the running progran without ctrl + q or ctrl + c (which prints out the error message). So is there any way which can allow me to stop the running program and return to the python >>> prompt by pressing some key defined by myself, say, ctrl + k . Thank you.

You can't use arbitrary keypresses, but to handle the normal interrupt (eg control-C) without errors all you need is to catch the KeyboardInterrupt exception it causes, ie, just wrap all of your looping code with

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

To "get control back" to the interactive prompt, the script must be running with -i (for "interactive"), or more advanced interactive Python shells like ipython must be used.

Provided that you are able to 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 use 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 are able to access the current environment.

Cheers Andrea

Are you running it from an iteractive prompt and want to just get back to the prompt. Or, are you running it from a shell and want to get to a python prompt in but with the current state of the programs execution?

For the later it you could the keyboard interupt exception in your code and break out to the python debugger (pdb).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM