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 whi开发者_如何学Pythonch 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 (e.g. control-C) without errors all you need is to catch the KeyboardInterrupt
exception it causes, i.e., 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()
精彩评论