PETER
PETER

Reputation: 59

how can I stop python script without killing it?

I want to know if there is a way to stop the python script when it is running, without killing it.

For example, I know ctrl + z or c will kill the current processes.. but I don't want to kill the program..

my python program takes one files at a time and execute some jobs.. each file takes about 10~20 minutes depends on the size of the file.. and there are many files in a directory..

but sometimes I have to let it finish the file that it is currently working on stop the program right after that current file instead of killing it in the middle of the work.

How can I do this in python? I want to write this python coding if I can..

I've tried

if os.path.exists(filename)
    sys exit(0)

but this one, I have to create a file while it is running so that when it reaches that file, it stops... but instead of doing this.. I want to see if there are better way to stop it.

Upvotes: 1

Views: 1772

Answers (3)

Gaur
Gaur

Reputation: 280

You can also catch the Interrupt Exception (Ctrl + C) and then process the unfinished file and come out of it.

`def main():
    try:
        for file in file_list:
            process(file)
    except KeyboardInterrupt:
        process(file)
        raise Exception`

Upvotes: 0

Kevin
Kevin

Reputation: 30181

but sometimes I have to let it finish the file that it is currently working on stop the program right after that current file instead of killing it in the middle of the work.

This is more specific than Ctrl+Z; you're asking to stop the program, but not right away. You can use signals for this. Set a signal handler with signal, and invoke it with kill -SIGWHATEVER at the command line. The signal handler, generally speaking, should just set a flag that you check periodically; it should not actually "do anything" by itself, since you don't know what state your program is in when it's called.

A signal handler is a function that gets called when your program receives a signal. They are set using signal.signal(). Signals are sent with the kill program, or the kill() system call. Your handler would look like this:

stop = False
def handler(number, frame):
    global stop
    stop = True
signal.signal(signal.SIGUSR1, handler)
for file in files:  # or whatever your main loop looks like
    # Process one file
    if stop:
        break

Upvotes: 4

shx2
shx2

Reputation: 64378

Ctrl+Z will only suspend the process, not kill it. You can later type fg to resume it ("fg" stands for "foreground". also, you can run "bg" for "background"). From what you describe, this sounds like a good solution to achieve what you want.

This, of course, applies to any process, not only python.

Upvotes: 1

Related Questions