복붙노트

[PYTHON] 주어진 wget 명령과 동일한 Python

PYTHON

주어진 wget 명령과 동일한 Python

이 wget 명령과 동일한 작업을 수행하는 Python 함수를 만들려고합니다.

wget -c --read-timeout=5 --tries=0 "$URL"

-c - 다운로드가 중단되면 중단 한 부분부터 계속합니다.

--read-timeout = 5 - 새 데이터가 5 초 이상 들어오지 않으면 포기하고 다시 시도하십시오. 주어진 -c는 이것이 중단 된 곳에서 다시 시도한다는 것을 의미합니다.

--tries = 0 - 영원히 다시 시도하십시오.

세 가지 인수를 함께 사용하면 다운로드가 실패 할 수 없습니다.

내 파이썬 스크립트에서 그 기능을 복제하고 싶지만 어디에서 시작해야할지 모르겠다.

해결법

  1. ==============================

    1.urllib.request가 작동해야합니다. 잠깐 (설정하지 않음) 루프를 설정하고, localfile이 이미 존재하는지 확인하고, RANGE 헤더가 포함 된 GET을 보내면 localfile을 얼마나 멀리 다운로드했는지 지정하십시오. 오류가 발생할 때까지 read ()를 사용하여 localfile에 추가하십시오.

    urllib.request가 작동해야합니다. 잠깐 (설정하지 않음) 루프를 설정하고, localfile이 이미 존재하는지 확인하고, RANGE 헤더가 포함 된 GET을 보내면 localfile을 얼마나 멀리 다운로드했는지 지정하십시오. 오류가 발생할 때까지 read ()를 사용하여 localfile에 추가하십시오.

    이것은 잠재적으로 네트워크 재 연결시 Python urllib2 resume download가 작동하지 않는 중복입니다.

  2. ==============================

    2.wget이라는 훌륭한 파이썬 모듈도있다. 꽤 사용하기 쉽다. 여기에서 찾았습니다.

    wget이라는 훌륭한 파이썬 모듈도있다. 꽤 사용하기 쉽다. 여기에서 찾았습니다.

    이는 디자인의 단순성을 보여줍니다.

    >>> import wget
    >>> url = 'http://www.futurecrew.com/skaven/song_files/mp3/razorback.mp3'
    >>> filename = wget.download(url)
    100% [................................................] 3841532 / 3841532>
    >> filename
    'razorback.mp3'
    

    즐겨.

    그러나 wget이 작동하지 않는 경우 (특정 PDF 파일에 문제가 있음)이 솔루션을 사용해보십시오.

    편집 : out 매개 변수를 사용하여 현재 작업 디렉토리 대신 사용자 정의 출력 디렉토리를 사용할 수도 있습니다.

    >>> output_directory = <directory_name>
    >>> filename = wget.download(url, out=output_directory)
    >>> filename
    'razorback.mp3'
    
  3. ==============================

    3.

    import urllib2
    
    attempts = 0
    
    while attempts < 3:
        try:
            response = urllib2.urlopen("http://example.com", timeout = 5)
            content = response.read()
            f = open( "local/index.html", 'w' )
            f.write( content )
            f.close()
            break
        except urllib2.URLError as e:
            attempts += 1
            print type(e)
    
  4. ==============================

    4.나는 wget에 컴파일 된 올바른 옵션이없는 Linux 버전에서 이와 같은 작업을 수행해야했습니다. 이 예제는 메모리 분석 도구 'guppy'를 다운로드하기위한 것입니다. 중요한지 아닌지는 잘 모르겠지만 대상 파일의 이름을 URL 대상 이름과 동일하게 유지했습니다 ...

    나는 wget에 컴파일 된 올바른 옵션이없는 Linux 버전에서 이와 같은 작업을 수행해야했습니다. 이 예제는 메모리 분석 도구 'guppy'를 다운로드하기위한 것입니다. 중요한지 아닌지는 잘 모르겠지만 대상 파일의 이름을 URL 대상 이름과 동일하게 유지했습니다 ...

    다음은 내가 생각해 낸 것입니다.

    python -c "import requests; r = requests.get('https://pypi.python.org/packages/source/g/guppy/guppy-0.1.10.tar.gz') ; open('guppy-0.1.10.tar.gz' , 'wb').write(r.content)"
    

    이것이 바로 한 줄짜리예요. 조금 더 읽기 쉽습니다.

    import requests
    fname = 'guppy-0.1.10.tar.gz'
    url = 'https://pypi.python.org/packages/source/g/guppy/' + fname
    r = requests.get(url)
    open(fname , 'wb').write(r.content)
    

    이것은 tarball을 다운로드 할 때 사용되었습니다. 다운로드 후 패키지를 추출하고 다운로드 할 수있었습니다.

    편집하다:

    질문을 처리하기 위해, STDOUT에 인쇄 된 진행 막대가있는 구현이 있습니다. 클린트 (clint) 패키지없이이 작업을 수행 할 수있는 더 이식성있는 방법이있을 수 있습니다. 그러나 이것은 내 컴퓨터에서 테스트되었고 잘 작동합니다.

    #!/usr/bin/env python
    
    from clint.textui import progress
    import requests
    
    fname = 'guppy-0.1.10.tar.gz'
    url = 'https://pypi.python.org/packages/source/g/guppy/' + fname
    
    r = requests.get(url, stream=True)
    with open(fname, 'wb') as f:
        total_length = int(r.headers.get('content-length'))
        for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1): 
            if chunk:
                f.write(chunk)
                f.flush()
    
  5. ==============================

    5.py로 쉽게 :

    py로 쉽게 :

    class Downloder():
        def download_manager(self, url, destination='Files/DownloderApp/', try_number="10", time_out="60"):
            #threading.Thread(target=self._wget_dl, args=(url, destination, try_number, time_out, log_file)).start()
            if self._wget_dl(url, destination, try_number, time_out, log_file) == 0:
                return True
            else:
                return False
    
    
        def _wget_dl(self,url, destination, try_number, time_out):
            import subprocess
            command=["wget", "-c", "-P", destination, "-t", try_number, "-T", time_out , url]
            try:
                download_state=subprocess.call(command)
            except Exception as e:
                print(e)
            #if download_state==0 => successfull download
            return download_state
    
  6. ==============================

    6.많은 파일을 다운로드하려는 경우를 대비해 스레드를 사용한 예제를 향상 시키십시오.

    많은 파일을 다운로드하려는 경우를 대비해 스레드를 사용한 예제를 향상 시키십시오.

    import math
    import random
    import threading
    
    import requests
    from clint.textui import progress
    
    # You must define a proxy list
    # I suggests https://free-proxy-list.net/
    proxies = {
        0: {'http': 'http://34.208.47.183:80'},
        1: {'http': 'http://40.69.191.149:3128'},
        2: {'http': 'http://104.154.205.214:1080'},
        3: {'http': 'http://52.11.190.64:3128'}
    }
    
    
    # you must define the list for files do you want download
    videos = [
        "https://i.stack.imgur.com/g2BHi.jpg",
        "https://i.stack.imgur.com/NURaP.jpg"
    ]
    
    downloaderses = list()
    
    
    def downloaders(video, selected_proxy):
        print("Downloading file named {} by proxy {}...".format(video, selected_proxy))
        r = requests.get(video, stream=True, proxies=selected_proxy)
        nombre_video = video.split("/")[3]
        with open(nombre_video, 'wb') as f:
            total_length = int(r.headers.get('content-length'))
            for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length / 1024) + 1):
                if chunk:
                    f.write(chunk)
                    f.flush()
    
    
    for video in videos:
        selected_proxy = proxies[math.floor(random.random() * len(proxies))]
        t = threading.Thread(target=downloaders, args=(video, selected_proxy))
        downloaderses.append(t)
    
    for _downloaders in downloaderses:
        _downloaders.start()
    
  7. from https://stackoverflow.com/questions/24346872/python-equivalent-of-a-given-wget-command by cc-by-sa and MIT license