1

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
Ali Sajjad
  • 3,589
  • 1
  • 28
  • 38
  • On Win, if you know the image name (aria2c.exe) you can use: taskkill /f /im aria2c.exe. This will kill the task and can be run via subprocess or directly in cmd. Is this something like what you’re after? – S3DEV Mar 27 '20 at 21:04

2 Answers2

1

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
SpaceKatt
  • 976
  • 6
  • 12
  • What does the value of __name__ actually means? – Ali Sajjad Mar 28 '20 at 15:01
  • 1
    It is a special variable that represents the context the script is running in. If it is the main script (i.e., being invoked as the top-level script `python your-top-level-script-name.py`), then this will run. It's a best practice because sometimes when you import a script, you dont want some code to run. That code you dont want to run should be in a block like above – SpaceKatt Mar 29 '20 at 01:54
1

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)
Isuru Dilshan
  • 719
  • 9
  • 18