logo

Python의 단순 다중 스레드 다운로드 관리자

에이 다운로드 관리자 기본적으로 인터넷에서 독립형 파일을 다운로드하는 작업 전용 컴퓨터 프로그램입니다. 여기서는 Python의 스레드를 사용하여 간단한 다운로드 관리자를 만들겠습니다. 멀티스레딩을 사용하면 여러 스레드에서 동시에 청크 형태로 파일을 다운로드할 수 있습니다. 이를 구현하기 위해 파일의 URL을 받아 다운로드하는 간단한 명령줄 도구를 만들겠습니다.

전제조건: Python이 설치된 Windows 머신.



설정

명령 프롬프트에서 아래 언급된 패키지를 다운로드합니다.

1. Click 패키지: Click은 필요한 만큼 적은 코드로 아름다운 명령줄 인터페이스를 만들기 위한 Python 패키지입니다. 명령줄 인터페이스 생성 키트입니다.

핍 설치 클릭



2. 요청 패키지: 이 도구에서는 URL(HTTP 주소)을 기반으로 파일을 다운로드합니다. Requests는 HTTP 요청을 보낼 수 있도록 Python으로 작성된 HTTP 라이브러리입니다. 간단한 Python 사전을 사용하여 데이터 다중 부분 파일과 매개변수에 헤더를 추가하고 동일한 방식으로 응답 데이터에 액세스할 수 있습니다.

pip 설치 요청

3. 스레딩 패키지: 스레드로 작업하려면 스레딩 패키지가 필요합니다.



pip 설치 스레딩

구현

메모:

프로그램은 이해하기 쉽도록 여러 부분으로 나누어져 있습니다. 프로그램을 실행하는 동안 코드의 일부가 누락되지 않았는지 확인하십시오.

1단계: 필수 패키지 가져오기

이러한 패키지는 웹 요청이 명령줄 입력을 처리하고 스레드를 생성하는 데 필요한 도구를 제공합니다.

Python
import click import requests import threading 

2단계: 핸들러 함수 생성

각 스레드는 이 함수를 실행하여 특정 파일 청크를 다운로드합니다. 이 함수는 특정 범위의 바이트만 요청하고 이를 파일의 올바른 위치에 쓰는 역할을 합니다.

Python
def Handler(start end url filename): headers = {'Range': f'bytes={start}-{end}'} r = requests.get(url headers=headers stream=True) with open(filename 'r+b') as fp: fp.seek(start) fp.write(r.content) 

3단계: 클릭으로 주요 기능 정의

함수를 명령줄 유틸리티로 전환합니다. 이는 사용자가 명령줄에서 스크립트와 상호 작용하는 방법을 정의합니다.

Python
#Note: This code will not work on online IDE @click.command(help='Downloads the specified file with given name using multi-threading') @click.option('--number_of_threads' default=4 help='Number of threads to use') @click.option('--name' type=click.Path() help='Name to save the file as (with extension)') @click.argument('url_of_file' type=str) def download_file(url_of_file name number_of_threads): 

4단계: 파일 이름 설정 및 파일 크기 결정

스레드 간에 다운로드를 나누고 서버가 범위 다운로드를 지원하는지 확인하려면 파일 크기가 필요합니다.

Python
 r = requests.head(url_of_file) file_name = name if name else url_of_file.split('/')[-1] try: file_size = int(r.headers['Content-Length']) except: print('Invalid URL or missing Content-Length header.') return 

5단계: 파일 공간 사전 할당

사전 할당은 특정 바이트 범위에 청크를 쓰기 전에 파일 크기가 올바른지 확인합니다.

Python
 part = file_size // number_of_threads with open(file_name 'wb') as fp: fp.write(b'' * file_size) 

6단계: 스레드 생성

스레드에는 병렬로 다운로드할 특정 바이트 범위가 할당됩니다.

Python
 threads = [] for i in range(number_of_threads): start = part * i end = file_size - 1 if i == number_of_threads - 1 else (start + part - 1) t = threading.Thread(target=Handler kwargs={ 'start': start 'end': end 'url': url_of_file 'filename': file_name }) threads.append(t) t.start() 

7단계: 스레드 조인

프로그램이 완료되기 전에 모든 스레드가 완료되도록 합니다.

추상 클래스와 인터페이스
Python
 for t in threads: t.join() print(f'{file_name} downloaded successfully!') if __name__ == '__main__': download_file() 

암호:

Python
import click import requests import threading def Handler(start end url filename): headers = {'Range': f'bytes={start}-{end}'} r = requests.get(url headers=headers stream=True) with open(filename 'r+b') as fp: fp.seek(start) fp.write(r.content) @click.command(help='Downloads the specified file with given name using multi-threading') @click.option('--number_of_threads' default=4 help='Number of threads to use') @click.option('--name' type=click.Path() help='Name to save the file as (with extension)') @click.argument('url_of_file' type=str) def download_file(url_of_file name number_of_threads): r = requests.head(url_of_file) if name: file_name = name else: file_name = url_of_file.split('/')[-1] try: file_size = int(r.headers['Content-Length']) except: print('Invalid URL or missing Content-Length header.') return part = file_size // number_of_threads with open(file_name 'wb') as fp: fp.write(b'' * file_size) threads = [] for i in range(number_of_threads): start = part * i # Make sure the last part downloads till the end of file end = file_size - 1 if i == number_of_threads - 1 else (start + part - 1) t = threading.Thread(target=Handler kwargs={ 'start': start 'end': end 'url': url_of_file 'filename': file_name }) threads.append(t) t.start() for t in threads: t.join() print(f'{file_name} downloaded successfully!') if __name__ == '__main__': download_file() 


코딩 부분이 완료되었으며 이제 아래 표시된 명령에 따라 .py 파일을 실행합니다.

python filename.py –-help

산출:

help_output' title=파이썬 파일명.py –-help


이 명령은 클릭 명령 도구의 사용법과 도구에서 허용할 수 있는 옵션을 보여줍니다. 다음은 URL에서 jpg 이미지 파일을 다운로드하고 이름과 스레드 수를 지정하는 샘플 명령입니다.

스크린샷-2025-04-07-155058' loading='lazy' title=jpg를 다운로드하는 샘플 명령

모든 것을 성공적으로 실행한 후에는 아래와 같이 폴더 디렉터리에서 파일(이 경우 flower.webp)을 볼 수 있습니다.

스크린샷-2025-04-07-155750' loading='lazy' title=예배 규칙서

마지막으로 우리는 성공적으로 작업을 마쳤으며 이는 Python에서 간단한 다중 스레드 다운로드 관리자를 구축하는 방법 중 하나입니다.