Home > Back-end >  How to kill a single process in Python at any point of its execution?
How to kill a single process in Python at any point of its execution?

Time:09-17

I'm fairly new to Python and have created an rudimentary application that runs a series of what is functionally macros for the user to automate some tedious processes with an existing application. Some of these processes take a while, and others I would like to run infinitely until a user hits a key to stop it. It is a small program and I was in a hurry, so the easiest solution was throwing a stop field into my classes and putting "if stop -> return/break" in numerous spots throughout my methods. The code below should demonstrate the general idea.

class ExampleClass:
  stop = false

  def stop_doing_stuff(self):
    stop = true

  def do_stuff(self):
    if stop:
      return
    else:
      for i in range(10000):
        if stop:
          return
        else:
          do_thing()

This seems clearly to me as an amateur solution, and I would like to know how this could be done better. I'm sure there is a way to accomplish this with threading, but I've only briefly worked with threads in the past so was not sure how at the time. I was most curious though as to whether there is perhaps an even easier solution which does not involve launching a thread since I'm in no need of multiple processes running concurrently.

Edit: I forgot to mention this is a GUI application running. The user is pressing buttons which will do the tasks for them. However, the GUI is hidden as a task is executed.

CodePudding user response:

You may catch a KeyboardInterrupt:

try:
    for i in range(10000):
        do_things()
except KeyboardInterrupt:
    return

CodePudding user response:

You can immediately terminate a script with a specified exit status using sys.exit(exit_status):

import sys

def foo():
    sys.exit(0) # exit with success status (zero)
    sys.exit(1) # exit with error status (non-zero)

If you want to terminate the script via keyboard you need only Ctrl C / Cmd C it. You can handle that interrupt gracefully using signal:

#!/usr/bin/env python
import signal
import sys

def signal_handler(sig, frame):
    print('You pressed Ctrl C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl C to terminate')

# ..perform work here..
  • Related