Kill only a subprocess created by python on CMD

220 Views Asked by At

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
2

There are 2 best solutions below

2
On BEST ANSWER

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
2
On

This code will open your EXE in the separate command prompt if your os is windows.

import os

if os.name == 'nt':
 os.system("start /wait cmd /c aria2c " + url + options)
else
 os.system("aria2c " + url + options)