A Beginner Guide to Python Use Aria2 to Download Files on Windows 10

By | April 30, 2020

Aria2 is a powerful tool to download files from internet. We can use python to call it to download our files. In this tutorial, we will introduce you how to do on windows 10.

Install aria2

To make python call aria2 application to download a file, we should install aria2 on windows 10 first. Here is an installation guide.

Install Aria2 on Win10 to Download Files: A Beginner Guide

Use python to call aria2c.exe

We can use python to run aria2c.exe to download our files. aria2c.exe is located in c:\aria2\aria2c.exe.

We can use python subprocess.Popen() to run aria2c.exe.

Implement Python subprocess.Popen(): Execute an External Command and Get Output

Create aria2 download command line

You should create an aria2 download command line. In this tutorial, we will use a command line like:

cmd = r'c:\aria2\aria2c.exe -d '+ save_dir +' -m 5 -o ' + out_filename + " "+ url

To know more about aria2 options, you can view:

https://aria2.github.io/manual/en/html/aria2c.html

Then we can create a python function to run aria2c.exe to download file, here is an example code.

import os
import subprocess

save_dir = r'F:\all-google-pdf\download'

def get_file_from_cmd(url, out_filename):
    cmd = r'c:\aria2\aria2c.exe -d '+ save_dir +' -m 5 -o ' + out_filename + " "+ url
    try:
        p1=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
        print("---start---")
        msg_content = ''
        for line in p1.stdout:
            print(line)
            l = line.decode(encoding="utf-8", errors="ignore")
            msg_content += l
        p1.wait()
        if '(OK):download completed' in msg_content:
            print("download by aira2 successfully.")
            return True
        return False
    except Exception as e:
        print(e)
        return False

We can use get_file_from_cmd() function to download files from internet.

How to use this function?

Here is an example:

url = 'http://www.al-edu.com/wp-content/uploads/2014/05/TheMotivationalHandbook.pdf'
get_file_from_cmd(url, 'test.pdf')

You will get a result like:

python run aira2 to download files

Leave a Reply