Search code examples
pythonpython-3.xcmdterminalaria2

Kill only a subprocess created by python on CMD


I have made a python script which downloads using aria2 downloader by running a shell command which can work on Windows and Linux.

os.system("aria2c " + url + options)
#some code I want to run if the process is stopped

Now, I want to test my program for the situation when file could not be downloaded. So, after executing the 'python downloader.py' on command-prompt (cmd.exe) Windows, I press Ctrl+C to stop only the download ('aria2c.exe' process only) but keep running my python code.

Doing this on Ubuntu terminal works fine! But on cmd windows, Ctrl+C stops 'aria2c.exe' process but also stops my python code. I want to know I can achieve this on command prompt?

If you need to know, this is what shows up on cmd:

    File "downloader.py", line 106, in download
      os.system(myCommand)
Keyboard interrupt

Solution

  • You could catch the KeyboardInterrupt exception, then execute the code you want to afterward.

    if __name__ == '__main__':
        try:
            os.system("aria2c " + url + options)
        except KeyboardInterrupt:
            print('Keyboard Interrupt Detected')
                # the rest of your code
                pass