1

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?

Aaron
  • 2,383
  • 3
  • 22
  • 53
Echows
  • 317
  • 2
  • 5
  • 14
  • 1
    Why not catch the exception and `break` whatever loop you're running? – jonrsharpe Mar 03 '15 at 14:10
  • It may happen that the script accidentally finishes just before it has a chance to handle the interruption and it ends up being caught by the interpreter. – BartoszKP Mar 03 '15 at 14:21
  • I don't think that is the case because if I don't have anything running in the interpreter, I can press ctrl + C as much as I want and the interpreter doesn't get killed. I think this behavior has something to do with the fact that I'm using an external (non-python) library inside my script and if I kill the script while it's executing something from these libraries the whole interpreter somehow dies. – Echows Mar 03 '15 at 16:37

1 Answers1

0

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()
motoku
  • 1,571
  • 1
  • 21
  • 49
  • I could of course do this, but I wouldn't like to clutter all my scripts with a try-catch logic just in case I sometimes want to stop the script. What I'm asking is how do I make the python interpreter work as it worked before, i.e. the interpreter never gets killed when I press Ctrl + C. In fact, now that I try, it doesn't kill the interpreter if I just press Ctrl+C while doing nothing. It only kills it occasionally when I'm running some script. – Echows Mar 03 '15 at 16:35
  • @Echows if the problem is intermittent, then you need to work on reproducing the problem. If you can't fix the issue once you discover it, then you can ask another question. – motoku Mar 03 '15 at 16:36