线程不终止

时间:2018-09-21 06:12:18

标签: python python-3.x urllib

程序运行正常,不会卡在最后:

   def process(self, task):
        global alive
        global dead
        global tested
        proxy = task
        log_msg = str("Trying HTTP proxy%21s " % proxy)

        cj = http.cookiejar.CookieJar()
        opener = urllib.request.build_opener(
                    urllib.request.HTTPCookieProcessor(cj),
                    urllib.request.HTTPRedirectHandler(),
                    urllib.request.ProxyHandler({'http': proxy})
        )

        try:
            t1 = time.time()
            response = opener.open(test_url, timeout=timeout_value).read()
            tested += 1
            t2 = time.time()
        except Exception as e:
            log_msg += "%s " % fail_msg
            print(Fore.LIGHTRED_EX + log_msg)
            dead += 1
            tested += 1
            return None

        log_msg += ok_msg + "Response time: %d" % (int((t2-t1)*1000))
        print(Fore.LIGHTGREEN_EX + log_msg)
        text_file = open(out_filename, "a")
        text_file.write(proxy + "\r\n")
        text_file.close()
        alive += 1

        # ctypes.windll.kernel32.SetConsoleTitleW(f"Proxy Checker [HTTP(s)] | Total proxies Left: {input_queue.qsize()} | Tested: {tested} | Alive: {alive} | Dead: {dead}")
        return proxy

但是,当我执行以下操作时,该程序并没有完成,并且在完成最新的代理检查时陷入了困境:

def process(self, task):
    global alive
    global dead
    global tested
    proxy = task
    log_msg = str("Trying HTTP proxy%21s " % proxy)

    cj = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(
                urllib.request.HTTPCookieProcessor(cj),
                urllib.request.HTTPRedirectHandler(),
                urllib.request.ProxyHandler({'http': proxy})
    )

    try:
        t1 = time.time()
        response = opener.open(test_url, timeout=timeout_value).read()
        tested += 1
        t2 = time.time()
    except Exception as e:
        log_msg += "%s " % fail_msg
        print(Fore.LIGHTRED_EX + log_msg)
        dead += 1
        tested += 1
        return None

    if "Connection working!" in response.decode('utf-8'):
        log_msg += ok_msg + "Response time: %d" % (int((t2-t1)*1000))
        print(Fore.LIGHTGREEN_EX + log_msg)
        text_file = open(out_filename, "a")
        text_file.write(proxy + "\r\n")
        text_file.close()
        alive += 1
        return proxy
    else:
        log_msg += "%s " % fail_msg
        print(Fore.LIGHTRED_EX + log_msg)
        dead += 1
        tested += 1
        return None

    # ctypes.windll.kernel32.SetConsoleTitleW(f"Proxy Checker [HTTP(s)] | Total proxies Left: {input_queue.qsize()} | Tested: {tested} | Alive: {alive} | Dead: {dead}")

我不明白为什么第一个代码有效,而第二个代码无效,我已经尝试了多次以找到解决方案,但我无法成功。 有关完整的工作代码,请参见此处:https://hastebin.com/epunisagah.py

0 个答案:

没有答案