Santi Peñate-Vera
Santi Peñate-Vera

Reputation: 1186

Stop python script without killing the python process

I would like to know if there is a way of programatically stopping a python script execution without killing the process like we do with this code:

import sys
sys.exit()

It would be the code equivalent to Ctrl+c

Upvotes: 9

Views: 30243

Answers (4)

Cameron Hyde
Cameron Hyde

Reputation: 118

Surely the simplest solution for the OP is raise KeyboardInterrupt?

This produces the same effect as ctrl+C in the terminal but can be called anywhere in the script. No need for import or further definition.

Upvotes: 3

Evandro Coan
Evandro Coan

Reputation: 9418

I had this problem while developing a Sublime Text packages. I was trying to stop a Sublime Text Python package, to test something while the package was being reloaded.

If I call sys.exit(), I kill Sublime Text python interpreter and need to restart Sublime Text. But after searching I figured it out the solution is pretty simple, I just need to call raise ValueError(), instead of sys.exit():

import sys
print(sys.path)

sys.exit()

-->

import sys
print(sys.path)

raise ValueError()

This will stop the python script execution right after running print(sys.path). Although it will print a big stack trace. But if you add the instruction sys.tracebacklimit = 1 before raise ValueError(), you reduce the stack trace call to one line:

import sys
print(sys.path)

raise ValueError()

-->

import sys
print(sys.path)

sys.tracebacklimit = 1
raise ValueError()

Related questions:

  1. Stop running python script without killing the interpreter
  2. Manually raising (throwing) an exception in Python

Upvotes: 6

Dan K.
Dan K.

Reputation: 41

Here is what I've found to work -- staying in the interpreter, while stopping a script.

# ------------------------------------------------------------------
# Reset so get full traceback next time you run the script and a "real"
# exception occurs
if hasattr (sys, 'tracebacklimit'):
    del sys.tracebacklimit

# ------------------------------------------------------------------
# Raise this class for "soft halt" with minimum traceback.
class Stop (Exception):
    def __init__ (self):
        sys.tracebacklimit = 0

# ==================================================================
# ... script here ...
if something_I_want_to_halt_on:
    raise Stop ()

# ... script continues ...

Upvotes: 4

Hugh Bothwell
Hugh Bothwell

Reputation: 56634

Define your own exception,

class HaltException(Exception): pass

and wrap the script in

try:
    # script goes here

    # when you want to stop,
    raise HaltException("Somebody stop me!")

except HaltException as h:
    print(h)
    # now what?

Upvotes: 10

Related Questions