在不杀死解释器的情况下停止运行python脚本 [英] Stop running python script without killing the interpreter
问题描述
之前,在解释器中,我可以通过按Ctrl + C
来杀死以execfile("somescript.py")
开头的python脚本,而不会杀死解释器.这将导致 KeyboardInterrupt
异常,该异常将停止脚本并让我再次使用解释器.但是,现在(我怀疑这是python的较新版本),当我在运行脚本时按Ctrl + C
时,它有时也会终止解释器,使我回到Linux命令行.由于某种原因,每次我用Ctrl + C
杀死脚本时,都不会发生这种情况.
Before, I were able to kill a python script started with execfile("somescript.py")
while in interpreter by pressing Ctrl + C
without killing the interpreter. This would cause a KeyboardInterrupt
exception that would stop the script and let me use the interpreter again. However, now (I suspect this came with newer version of python), when I press Ctrl + C
while running a script, it sometimes also kills the interpreter, throwing me back to Linux command line. For some reason this doesn't happen every time I kill a script with Ctrl + C
.
这很烦人,因为我经常交互使用python解释器,即我用execfile("somescript.py")
运行一些脚本,处理它在解释器中生成的数据,等等.以前,如果某些脚本卡住了,我可以杀死而不丢失它在卡住之前计算出的数据(或我存储在变量中的数据).
This is annoying because I often use python interpreter interactively, i.e. I run some script with execfile("somescript.py")
, play around with the data it produces in the interpreter, etc. Before, if some script got stuck, I was able to kill it and not lose the data it had calculated (or I had stored in variables) before getting stuck.
所以我的问题是,如何立即在解释器中杀死以execfile()
开头的python脚本而又不杀死解释器?
So my question is, how do I kill a python script started with execfile()
in the interpreter now without killing the interpreter?
推荐答案
通常,这是通过try
语句完成的:
Usually, this is done with a try
statement:
>>> def f():
... try:
... exec(open("somefile.py").read())
... except Exception as e: print(e)
...
>>> f()
^CTraceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in f
File "<string>", line 4, in <module>
File "<string>", line 3, in g
KeyboardInterrupt
>>>
somefile.py
:
def g():
while True: pass
g()
这篇关于在不杀死解释器的情况下停止运行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!