Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ctrl C won't kill looped subprocess in Python

Is there a proper way to create a script that loops through files in a folder and executes a subprocess that can be externally killed with Ctrl C? I have something like the following embedded in a pipeline and cannot Ctrl C it from the command line when the main process is killed.

Example script:

import subprocess
import os
import sys

input_directory = sys.argv[1]

for file in os.listdir(os.path.abspath(input_directory)):
    output = file + "_out.out"
    command = ['somescript.py', file, output]
    try:
        subprocess.check_call(command)
    except:
        print "Command Failed"

I would then execute program:

Example_script.py /path/to/some/directory/containing/files/

While it is looping, if I see the command failed, I want use Ctrl C. However, it fails and continues to run additional subprocesses despite the main script has been destroyer with Ctrl C. Is there a proper way to write something like this that can kill the childs (additional subprocess) with Ctrl C?

Any help, or pointing me in the direction is appreciated greatly. I am currently looking for a good method to do.

like image 630
SIO Avatar asked Apr 07 '26 02:04

SIO


1 Answers

What you have in your try/except block is too permissive, such that when Ctrl+C is pressed, the KeyboardInterrupt exception is also handled by that same exception handler as the one that print "Command Failed", and as that is now properly handled there, the flow of the program is continued through the for loop. What you should do is:

  1. Replace except: with except Exception: so that the KeyboardInterrupt exception will not be trapped, such that any time Ctrl+C is pressed the program will terminate (including subprocesses that isn't stuck in some non-terminatable state);
  2. After the print statement, break out of the loop to prevent further execution from happening, if that is the intended behavior that you want this program to do.
like image 111
metatoaster Avatar answered Apr 09 '26 14:04

metatoaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!