简体   繁体   中英

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM