PETER
PETER

Reputation: 59

How to stop the python script

I am trying to write a python script that also deals killing/stopping its own process with the signals.

It runs each files one at a time, sleep at specific time and run again until it finished the whole directory with files. The processing time of each file is around 5 to 10 minutes depending on the size.

However, I want my program to stop when I give the signal. It should not kill it right away. It should run the current file and stop afterwards.

So I cannot use CTRL Z because it suspends the pid right away.

stop = False
def handler(number, frame):
    global stop
    stop = True
signal.signal(signal.SIGUSR1, handler)
while not stop:
    # Do things

Above is what I tried, but it kills it right away when I signal. Also it goes into an infinite loop even after it finishes working on all the files.

What can I do to stop the process when I signal, allowing it to finish processing the current file first?

Upvotes: 2

Views: 1054

Answers (2)

jsbueno
jsbueno

Reputation: 110726

Just install a signal handler for signal.SIGTERM - and within it setup a state variable in your program that you check when finishing processing each file.

It is actually quite simple - see the documentation at: https://docs.python.org/2/library/signal.html .

import os 
import signal
terminate = False

for filename in os.listdir("<your dir>"):
    if terminate:
       break
    process_next_file(filename)

def handler(signum, frame):
    global terminate
    print("Termination requested")
    terminate = True

signal.signal(signal.SIGTERM, handler)

(Also, you can use other signals - SIGINT is the one used when the user press ctrl+C for example)

Upvotes: 1

Q Q
Q Q

Reputation: 273

You can create a command listener thread. Main thread still does file processing. For example, the listener thread waits a command from standard input. When you send "stop" command, it sets a varible. The file processor thread checks the variable before processing a file. So, it can stop when you want to stop processing.

Upvotes: 1

Related Questions