简体   繁体   English

如何退出运行python程序到python提示符?

[英]How to quit the running python program to python prompt?

I wrote a implementation of conway's game of life. 我写了一个conway的生活游戏的实现。 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). 对于自动模式,我无法在没有ctrl + qctrl + c (打印出错误信息)的情况下停止正在运行的程序。 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 . 那么有什么方法可以让我停止正在运行的程序并通过按下我自己定义的一些键来返回到python >>>提示符,例如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 你不能使用任意的按键,但是为了处理正常的中断(例如control-C)而没有错误你只需要捕获它引起的KeyboardInterrupt异常,即只需用你的所有循环代码包装它

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. 要“控制回”到交互式提示符,脚本必须使用-i (用于“交互式”)运行,或者必须使用更高级的交互式Python shell,如ipython。

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: 或者如果你使用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. 这将打开一个python或IPython shell,您可以在其中访问当前环境。

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? 或者,你是从shell运行它,并希望得到一个python提示符,但具有程序执行的当前状态?

For the later it you could the keyboard interupt exception in your code and break out to the python debugger (pdb). 对于后者,您可以在代码中使用键盘中断异常并跳转到python调试器(pdb)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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