Command Line File Downloader in Python
Python is one of the most popular general-purpose programming languages with a wide range of use cases from general coding to complex fields like AI. One of the reasons for such popularity of python as a programming language is the availability of many built-in as well as third-party libraries and packages.
In this article, we are going to build a simple command-line file downloader, which you can download a file if you have the download link.
We are going to download files over HTTP instead of FTP. Once we have made the request for the file, we will use the response as an input stream to write or save the file to the file system. While Downloading, details like download speed, time, and amount of file downloaded will be shown.
- Take the file URL via command line
- Open the file input or download stream over HTTP via requests.
- Download the file by writing the file in chunks from the download/input stream into the file system.
- Display the details
- Save the file.
Step 1: Libraries required
Step 2: a dictionary for detecting file size in proper units
While Downloading the file, parameters like speed, size, time will be shown. So let’s see how to do this. Dictionary for getting file size and download speed unit depending on the amount downloaded takes sizes in bytes.
Function for checking units of the length of the file downloaded. Length is in bytes so corresponding units are checked.
Step 3: Downloading file over HTTP
We will open a file stream over HTTP using requests and then save the data in chunks to the local file. Let’s see how the code will look and then put it all together.
Step 4: Printing output
The output will consist of a dynamic progress bar with downloading details. For this we use stdout.write() and stdout.flush() methods
Below is the full implementation:
Save the code in a python file and use it as follows
python <program_name>.py <file_link> <save_location(by default '.')>