Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Command Line File Downloader in Python
Python provides powerful libraries for creating command line applications. A command line file downloader allows you to download files from the internet directly through your terminal without using a browser.
This tutorial shows how to build a simple file downloader using Python's requests and argparse libraries. The application accepts a URL and filename as command line arguments and downloads the file to your local system.
Required Libraries
We need two Python libraries for this project:
- requests For making HTTP requests to download files
- argparse For handling command line arguments
Install the requests library using pip (argparse is built into Python):
pip install requests
Building the File Downloader
Step 1: Import Required Libraries
Start by importing the necessary libraries ?
import requests import argparse
Step 2: Create the Download Function
Define a function that downloads a file from a given URL and saves it locally ?
def download_file(url, filename):
try:
response = requests.get(url)
response.raise_for_status() # Raises an HTTPError for bad responses
with open(filename, "wb") as f:
f.write(response.content)
return True
except requests.exceptions.RequestException as e:
print(f"Error downloading file: {e}")
return False
This function uses requests.get() to fetch the file content and writes it to a local file in binary mode. The with statement ensures the file is properly closed after writing.
Step 3: Parse Command Line Arguments
Set up argument parsing to handle URL and filename inputs ?
def main():
parser = argparse.ArgumentParser(description="Download files from URLs")
parser.add_argument("--url", help="URL of the file to download", required=True)
parser.add_argument("--filename", help="Local filename to save as", required=True)
args = parser.parse_args()
return args
Step 4: Complete Implementation
Here's the complete command line file downloader ?
import requests
import argparse
def download_file(url, filename):
try:
print(f"Downloading {url}...")
response = requests.get(url)
response.raise_for_status()
with open(filename, "wb") as f:
f.write(response.content)
print(f"File downloaded successfully as {filename}")
return True
except requests.exceptions.RequestException as e:
print(f"Error downloading file: {e}")
return False
def main():
parser = argparse.ArgumentParser(description="Download files from URLs")
parser.add_argument("--url", help="URL of the file to download", required=True)
parser.add_argument("--filename", help="Local filename to save as", required=True)
args = parser.parse_args()
download_file(args.url, args.filename)
if __name__ == "__main__":
main()
Usage Example
Save the code as downloader.py and run it from the command line ?
python downloader.py --url https://httpbin.org/json --filename sample.json
This command downloads the JSON data from httpbin.org and saves it as sample.json in your current directory.
Enhanced Features
You can extend this downloader with additional features ?
import requests
import argparse
import os
from urllib.parse import urlparse
def download_file_with_progress(url, filename=None):
try:
# Generate filename from URL if not provided
if not filename:
parsed_url = urlparse(url)
filename = os.path.basename(parsed_url.path) or "downloaded_file"
response = requests.get(url, stream=True)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
downloaded = 0
with open(filename, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
downloaded += len(chunk)
if total_size > 0:
percent = (downloaded / total_size) * 100
print(f"\rProgress: {percent:.1f}%", end="")
print(f"\nFile downloaded successfully as {filename}")
return True
except requests.exceptions.RequestException as e:
print(f"Error downloading file: {e}")
return False
Conclusion
Building a command line file downloader in Python is straightforward using the requests and argparse libraries. This tool provides a convenient way to download files programmatically and can be extended with features like progress bars, resume capability, and error handling for production use.
