We are going to use the threading module to download multiple files concurrently.
However, note that for I/O-bound tasks, multithreading can be beneficial in Python due to the Global Interpreter Lock (GIL) releasing during I/O operations.
Steps:
- We will have a list of URLs.
- For each URL, we will define a function that downloads the file and saves it to a specified location.
- We will create a thread for each URL and start them.
- We will wait for all threads to finish.
But note: creating too many threads at once might be overwhelming for the system and the server.
We can use a thread pool to limit the number of concurrent downloads.
Alternatively, we can use concurrent.futures.ThreadPoolExecutor which is more convenient.
Let's design:
- We'll use
requests to download the files. If not installed, we can install it via pip.
- We'll also handle potential errors (like network issues, invalid URL, etc.)
However, the problem says to use multithreading, so we'll use ThreadPoolExecutor from concurrent.futures.
Steps with ThreadPoolExecutor:
- Create a list of URLs.
- Define a function that takes a URL and downloads it, returning the content or saving the file.
- Use
ThreadPoolExecutor to map the function to the list of URLs.
But note: if we have a lot of URLs, we don't want to create too many threads at once. We can set the max_workers.
However, the problem does not specify the number of URLs, so we can either:
a) Let ThreadPoolExecutor decide (by default, it uses 5 * number of cores, but we can set it to a fixed number or based on the number of URLs)
b) Set a fixed number of workers, say 10.
Let's assume we want to download all the files and save them in the current directory with the filename being the last part of the URL.
Example URL: http://example.com/file1.zip -> save as file1.zip
We'll extract the filename from the URL. If the URL doesn't have a filename, we can generate one.
However, sometimes the URL might not have a proper filename. We can use:
- The last part after splitting by '/'
- If that's empty, we can use a default name with an index.
But also, we should check the Content-Disposition header for a filename? That might be overkill for a simple script.
Let's keep it simple: use the last part of the URL. If it's empty, use "file_{index}".
Steps for the download function:
- Send a GET request to the URL.
- Check if the request was successful (status code 200).
- Determine the filename:
filename = url.split('/')[-1]
if not filename:
filename = f"file_{i}" # but we don't have i in the function? We can pass an index or use the URL as a key?
Alternatively, we can return the content and let the main thread save? But that would require passing the index.
Let's change: we'll pass a tuple (url, index) or (url, filename) to the download function.
However, the problem says: "from a list of URLs", so we don't have filenames. We can generate a unique name for each.
Let's do:
def download_file(url, index=None):
response = requests.get(url, stream=True)
if response.status_code == 200:
# Try to get filename from URL
filename = url.split('/')[-1]
if not filename:
# If the URL ends with a slash, we use the index
filename = f"file_{index}" if index is not None else "file"
# But also, sometimes the URL might have query parameters, we should remove them?
# Let's remove everything after '?' in the filename part.
filename = filename.split('?')[0]
# If the filename is still empty, use the index.
if not filename:
filename = f"file_{index}" if index is not None else "file"
with open(filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
return f"Downloaded {url} as {filename}"
else:
return f"Failed to download {url}: status code {response.status_code}"
Then, we can use:
with ThreadPoolExecutor(max_workers=10) as executor:
futures = [executor.submit(download_file, url, i) for i, url in enumerate(urls)]
for future in futures:
print(future.result())
But note: if two URLs have the same filename, we might overwrite. We can use the index to make it unique.
Alternatively, we can use the index in the filename always? But then we lose the original name.
Let's adjust: if the filename from URL is not empty, we use it, but if there's a duplicate, we can add a number?
That complicates things. For simplicity, we'll use:
filename = f"{index}_{url.split('/')[-1].split('?')[0]}"
if not filename.split('_')[1]: # meaning the part after index_ is empty?
filename = f"file_{index}"
But that might be messy.
Alternatively, we can just use the index as the filename and then rename? Or we can use the index and the last part of the URL.
Let me re-think: we want to preserve the original filename if possible, but avoid collisions.
We can do:
base = url.split('/')[-1].split('?')[0]
if not base:
base = f"file_{index}"
filename = f"{index}_{base}"
But then the filename becomes "0_file1.zip", which is a bit odd.
Another idea: use the original filename if it's non-empty, and if there's a duplicate, then add a number.
But to keep it simple, we'll just use the index and the original filename (if non-empty) without worrying about duplicates because the index is unique.
So:
base = url.split('/')[-1].split('?')[0]
if base:
filename = f"{index}_{base}"
else:
filename = f"file_{index}"
This way, each file gets a unique name (because index is unique) and we keep the original name if present.
However, if two URLs have the same base name, then we get two different filenames (because of the index prefix). That's acceptable.
But note: the index is just the order in the list. It's arbitrary. We can also use a random string? Not necessary.
Let's go with that.
However, the user might not want the index prefix. But the problem doesn't specify.
Since the problem says "download multiple files from a list of URLs", we are not told how to name them.
We can also let the user specify a directory? But the problem doesn't say.
Let's stick to the current directory and the above naming.
Alternatively, we can change the function to take an optional output directory? But again, the problem doesn't specify.
We'll keep it simple and save in the current directory.
But note: if the URL has no filename, we use "file_{index}" without a prefix? Then two URLs with no filename would be "file_0", "file_1", which is fine.
Let me adjust:
base = url.split('/')[-1].split('?')[0]
if base:
filename = f"{index}_{base}"
else:
filename = f"file_{index}"
This will produce:
URL: http://example.com/file.zip -> 0_file.zip
URL: http://example.com/ -> file_1
But wait, for the second, base is empty? Because splitting by '/' and taking last of "http://example.com/" gives empty string.
So we get "file_1". That's acceptable.
However, what if the URL is "http://example.com"? Then split by '/' -> ['http:', '', 'example.com'] -> last is 'example.com', so base is 'example.com'. Then we get "1_example.com". That's a file without extension? It's okay.
Alternatively, we can use the netloc (domain) as the base if the last part is empty? But the problem doesn't specify.
We'll stick to the above.
But note: if the URL has a path that ends with a slash, then the last part is empty. We are handling that.
Let's code accordingly.
However, we might run into issues with very long filenames or illegal characters? We can use a safer approach.
We can use os.path.basename and then remove query string? But os.path.basename works on paths, and URLs are not paths.
Alternatively, we can use urllib.parse to parse the URL and get the path, then take the last part.
Let's use urllib.parse:
from urllib.parse import urlparse
parsed = urlparse(url)
path = parsed.path
base = path.split('/')[-1] if path else ''
Then proceed as above.
But note: the path might be empty, then we get empty string.
We'll do:
from urllib.parse import urlparse
parsed = urlparse(url)
path = parsed.path
base = path.split('/')[-1] if path else ''
Then if base is empty, we use the index.
But wait, what if the URL is like "http://example.com"? Then path is empty? Actually, the path of "http://example.com" is empty string? Yes.
So base would be empty, then we use "file_{index}".
But the domain is "example.com", so maybe we want to use that? The problem doesn't specify.
We'll stick to the above.
Let's write the function accordingly.
However, note that the URL might have a fragment? We don't want that. The urlparse separates fragment.
We are only using the path, so it's safe.
Steps:
import requests
from urllib.parse import urlparse
from concurrent.futures import ThreadPoolExecutor
def download_file(url, index):
try:
response = requests.get(url, stream=True, timeout=10)
response.raise_for_status() # Will raise an exception for 4xx/5xx status
parsed = urlparse(url)
path = parsed.path
base = path.split('/')[-1] if path else ''
if base:
filename = f"{index}_{base}"
else:
filename = f"file_{index}"
# Remove any query parameters from the base? We already have only the path, so no query.
# But note: the path might have a query? No, because we used urlparse and took path.
with open(filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
return f"Downloaded {url} as {filename}"
except Exception as e:
return f"Error downloading {url}: {e}"
Then:
urls = [ ... list of urls ... ]
with ThreadPoolExecutor(max_workers=10) as executor:
futures = [executor.submit(download_file, url, i) for i, url in enumerate(urls)]
for future in futures:
print(future.result())
But note: if the list is very long, we are creating a list of futures and then iterating. That's okay.
Alternatively, we can use executor.map but then we lose the index? We can do:
with ThreadPoolExecutor(max_workers=10) as executor:
results = executor.map(lambda pair: download_file(pair[1], pair[0]), enumerate(urls))
for result in results:
print(result)
But the lambda might be less readable.
We can also do:
with ThreadPoolExecutor(max_workers=10) as executor:
futures = []
for i, url in enumerate(urls):
futures.append(executor.submit(download_file, url, i))
for future in concurrent.futures.as_completed(futures):
print(future.result())
This way we print as soon as a download finishes, but the order might be different.
The problem doesn't specify the order of output.
Let's use the first approach with a list and then print in order? But then we wait for all to finish.
Alternatively, we can use as_completed to print as they complete.
We'll do:
from concurrent.futures import ThreadPoolExecutor, as_completed
with ThreadPoolExecutor(max_workers=10) as executor:
future_to_url = {executor.submit(download_file, url, i): i for i, url in enumerate(urls)}
for future in as_completed(future_to_url):
i = future_to_url[future]
try:
result = future.result()
print(f"URL {i}: {result}")
except Exception as e:
print(f"URL {i} generated an exception: {e}")
But our download_file already catches exceptions and returns a string.
So we can just:
for future in as_completed(future_to_url):
i = future_to_url[future]
print(f"URL {i}: {future.result()}")
This will print in the order of completion.
We'll let the user decide? The problem doesn't specify.
Since the problem says "download multiple files concurrently", we are doing that.
Let me write the full script.
We'll also add a check for the requests module.
But the problem says to write a script, so we assume the environment has requests.
If not, we can catch the ImportError and give a message.
Let's do:
try:
import requests
except ImportError:
print("Please install requests: pip install requests")
sys.exit(1)
We'll also import sys.
Let's put it all together.
However, note: the function download_file uses requests and urlparse. We must import them.
We are going to write:
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlparse
import requests
Then the function and main.
We'll define the list of URLs in the script for example, but we can also read from a file or command line? The problem says "from a list of URLs", so we'll define a list.
Example:
urls = [
"http://example.com/file1.zip",
"http://example.com/file2.jpg",
...
]
We'll let the user modify the list.
Alternatively, we can read from a file? The problem doesn't specify.
We'll stick to a list in the script.
Let me write the full script.
Note: We set a timeout for the request? We set 10 seconds. We can make it configurable.
But the problem doesn't specify.
We'll set a timeout to avoid hanging.
Let's code accordingly.
Also, we are using stream=True to avoid loading the entire file into memory.
We are writing in chunks.
This should be efficient.
Let's write the script.
Here's a Python script that uses multithreading to download files concurrently from a list of URLs. It uses concurrent.futures.ThreadPoolExecutor for clean thread management and requests for HTTP downloads.
import os
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlparse
import time
def download_file(url, save_dir='downloads', chunk_size=8192, timeout=30):
"""
Download a single file from a URL.
Args:
url (str): The URL to download from
save_dir (str): Directory to save the file
chunk_size (int): Size of chunks to download at a time
timeout (int): Request timeout in seconds
Returns:
tuple: (url, filename, success, message)
"""
try:
# Create the save directory if it doesn't exist
os.makedirs(save_dir, exist_ok=True)
# Extract filename from URL
parsed_url = urlparse(url)
filename = os.path.basename(parsed_url.path)
# If no filename in URL, generate one
if not filename:
filename = f"download_{hash(url) % 10000}_{int(time.time())}"
# Full path to save the file
filepath = os.path.join(save_dir, filename)
# Make the request with streaming
response = requests.get(url, stream=True, timeout=timeout)
response.raise_for_status() # Raise exception for bad status codes
# Save the file in chunks
with open(filepath, 'wb') as f:
for chunk in response.iter_content(chunk_size=chunk_size):
if chunk: # Filter out keep-alive chunks
f.write(chunk)
return (url, filename, True, f"Downloaded successfully to {filepath}")
except requests.exceptions.RequestException as e:
return (url, None, False, f"Request failed: {str(e)}")
except IOError as e:
return (url, None, False, f"File save failed: {str(e)}")
except Exception as e:
return (url, None, False, f"Unexpected error: {str(e)}")
def download_concurrently(urls, max_workers=5, save_dir='downloads'):
"""
Download multiple files concurrently using thread pool.
Args:
urls (list): List of URLs to download
max_workers (int): Maximum number of concurrent downloads
save_dir (str): Directory to save files
Returns:
list: Results for each download attempt
"""
results = []
with ThreadPoolExecutor(max_workers=max_workers) as executor:
# Submit all download tasks
future_to_url = {
executor.submit(download_file, url, save_dir): url
for url in urls
}
# Process completed tasks as they finish
for future in as_completed(future_to_url):
url = future_to_url[future]
try:
result = future.result()
results.append(result)
except Exception as e:
results.append((url, None, False, f"Task failed: {str(e)}"))
return results
def main():
# Example list of URLs to download
urls = [
'https://example.com/file1.zip',
'https://example.com/file2.pdf',
'https://example.com/file3.jpg',
# Add more URLs as needed
]
# Configuration
MAX_WORKERS = 5 # Adjust based on your network and system capabilities
SAVE_DIRECTORY = 'downloads'
print(f"Starting download of {len(urls)} files with {MAX_WORKERS} workers...")
print(f"Files will be saved to: {os.path.abspath(SAVE_DIRECTORY)}\n")
# Record start time
start_time = time.time()
# Download concurrently
results = download_concurrently(urls, MAX_WORKERS, SAVE_DIRECTORY)
# Record end time
end_time = time.time()
# Print results
print("\n" + "="*50)
print("DOWNLOAD RESULTS:")
print("="*50)
successful = 0
failed = 0
for url, filename, success, message in results:
status = "✓ SUCCESS" if success else "✗ FAILED"
print(f"{status}: {url}")
if filename:
print(f" Saved as: {filename}")
print(f" Message: {message}\n")
if success:
successful += 1
else:
failed += 1
# Print summary
print("="*50)
print("SUMMARY:")
print(f"Total files: {len(urls)}")
print(f"Successful: {successful}")
print(f"Failed: {failed}")
print(f"Time taken: {end_time - start_time:.2f} seconds")
print("="*50)
if __name__ == "__main__":
# Check if requests is installed
try:
import requests
except ImportError:
print("Error: The 'requests' library is required.")
print("Please install it using: pip install requests")
exit(1)
main()
Key Features:
- Concurrent Downloads: Uses
ThreadPoolExecutor to download multiple files simultaneously.
- Error Handling: Each download is wrapped in try-catch to handle individual failures without stopping others.
- Streaming Downloads: Uses
stream=True to handle large files without loading everything into memory.
- Progress Tracking: Uses
as_completed() to process results as soon as they're available.
- Smart Filename Extraction: Extracts filenames from URLs or generates unique names when needed.
- Configurable: Adjust
max_workers based on your network capacity (typical values: 3-10).
- Directory Management: Automatically creates the download directory.
Installation:
pip install requests
Usage:
- Modify the
urls list in the main() function with your actual URLs.
- Adjust
MAX_WORKERS based on your needs (more workers = more concurrent downloads, but may hit server limits or network bandwidth).
- Run the script:
python downloader.py
Important Notes:
- Rate Limiting: Some servers may block you if you make too many concurrent requests. Adjust
MAX_WORKERS accordingly.
- Legal Compliance: Ensure you have permission to download the files and respect
robots.txt and terms of service.
- Network Impact: Concurrent downloads can saturate your bandwidth. Consider adding delays if needed.
- File Conflicts: If multiple URLs have the same filename, later downloads will overwrite earlier ones. Consider adding timestamps or unique identifiers to filenames if this is a concern.
Alternative with Rate Limiting:
If you need to limit the request rate, add a delay between starting downloads:
import time
# In download_concurrently function:
for i, url in enumerate(urls):
if i > 0:
time.sleep(0.5) # 500ms delay between starting each download
future = executor.submit(download_file, url, save_dir)
future_to_url[future] = url
This script provides a robust foundation for bulk file downloads with proper error handling and concurrent execution.