Stop running python script without killing the interpreter

烂漫一生 提交于 2019-12-11 09:34:27

问题


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.

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.

So my question is, how do I kill a python script started with execfile() in the interpreter now without killing the interpreter?


回答1:


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()


来源:https://stackoverflow.com/questions/28833658/stop-running-python-script-without-killing-the-interpreter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!