2012-02-14 90 views
1

好球員,我在谷歌搜索,並在這裏對計算器這個答案,並在數小時後,沒有看到一個工作腳本來做到這一點的一個正確的答案....蟒蛇的urllib2超時

在這裏,我粘貼假設的python工作腳本的4個示例,爲超時設置的套接字和/或超時參數設置不存在的url的默認超時值。

沒有人工作,所以超時從不觸發。

任何想法?

首先〔實施例:

import urllib2 

try:     
    header_s = {"User-Agent":"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"} 

    req = urllib2.Request("http://www.nonexistantdomainurl.com/notexist.php",headers = header_s) 


    print urllib2.urlopen(req, None, 5.0).read() 

except urllib2.URLError, e: 
    print "Url Error: %r" % e 

except Exception,e: 
    print "Fallo de tipo ",e 

else: 
    print "all ok!" 

第二個例子:

import urllib2 

try: 
    response = urllib2.urlopen("http://www.nonexistantdomainurl.com/notexist.php", None, 2.5) 
except urllib2.URLError, e: 
    print "Oops, timed out?" 

THRID例如:

from urllib2 import Request, urlopen, URLError, HTTPError 
import base64 


req = Request('http://www.nonexistantdomainurl.com/notexist.php') 

try: 
    response = urlopen(req,timeout=5.0) 

except HTTPError, e: 
    print 'The server couldn\'t fulfill the request.' 
    print 'Error code: ', e.code 
except URLError, e: 
    print 'We failed to reach a server.' 
    print 'Reason: ', e.reason 

第四個例子:

import urllib2 
import socket 


socket.setdefaulttimeout(5) 

try: 
    response = urllib2.urlopen("http://www.faluquito.com/equipo.php",timeout=5.0).read() 


except urllib2.URLError, e: 
    print "Url Error: %r" % e 
+0

可能的解釋:http://stackoverflow.com/a/8028602/190597 – unutbu 2012-02-14 12:55:35

+0

謝謝@unutbu但這是另一種情況與超時問題無關。在那裏,她想知道如何在發送不好的地點時變成200。 – dyoser 2012-02-14 14:56:35

回答

4
>>> import urllib2 
>>> import time 
>>> import contextlib 
>>> 
>>> def timeit(): 
... s = time.time() 
... try: 
...  yield 
... except urllib2.URLError: 
...  pass 
... print 'took %.3f secs' % (time.time() - s) 
... 
>>> timeit = contextlib.contextmanager(timeit) 
>>> with timeit(): 
... r = urllib2.urlopen('http://loc:8080', None, 2) 
... 
took 2.002 secs 
>>> with timeit(): 
... r = urllib2.urlopen('http://loc:8080', None, 5) 
... 
took 5.003 secs 
+0

不錯的做法,但嘗試使用此命令:r = urllib2.urlopen('http://www.faluquito.com/equipo.php',None.5)...並看看會發生什麼。另外我在你的終端上試過你的例子,它永遠不會達到2或5秒......它花費了0.145秒,所以...... – dyoser 2012-02-14 12:27:09

+0

@dyoser,別忘了明確指定協議'http://'。我試圖連接到你的'http:// faluquito.com/equipo.php'。它經常需要大約10秒,我認爲問題在於域名解析,連接似乎被委託給阻塞的OS例程,並且在控制位於Python之後立即退出。但我可能是錯的。 – newtover 2012-02-14 13:52:33

+0

這是因爲編輯沒有顯示它:)但它是(http:// www我的意思是)..是的,這似乎是像你說的那樣工作,所以在某些情況下超時是無用的。 – dyoser 2012-02-14 14:26:04

1

如果你的機器有UNIX程序掏,你可以找出這樣的不存在的網址:

import logging 
import subprocess 
import shlex 

logging.basicConfig(level = logging.DEBUG, 
        format = '%(asctime)s %(module)s %(levelname)s: %(message)s', 
        datefmt = '%M:%S') 
logger = logging.getLogger(__name__) 

urls = ['http://1.2.3.4', 
     "http://www.nonexistantdomainurl.com/notexist.php", 
     "http://www.faluquito.com/equipo.php", 
     'google.com'] 

nonexistent = ['63.251.179.13', '8.15.7.117'] 
for url in urls: 
    logger.info('Trying {u}'.format(u=url)) 

    proc = subprocess.Popen(shlex.split(
     'dig +short +time=1 +retry=0 {u}'.format(u = url)), 
          stdout = subprocess.PIPE, stderr = subprocess.PIPE) 
    out, err = proc.communicate() 
    out = out.splitlines() 
    logger.info(out) 
    if any(addr in nonexistent for addr in out): 
     logger.info('nonexistent\n') 
    else: 
     logger.info('success\n') 

在我的機器,這產生了:

00:57 test INFO: Trying http://1.2.3.4 
00:58 test INFO: ['63.251.179.13', '8.15.7.117'] 
00:58 test INFO: nonexistent 

00:58 test INFO: Trying http://www.nonexistantdomainurl.com/notexist.php 
00:58 test INFO: ['63.251.179.13', '8.15.7.117'] 
00:58 test INFO: nonexistent 

00:58 test INFO: Trying http://www.faluquito.com/equipo.php 
00:58 test INFO: ['63.251.179.13', '8.15.7.117'] 
00:58 test INFO: nonexistent 

00:58 test INFO: Trying google.com 
00:58 test INFO: ['72.14.204.113', '72.14.204.100', '72.14.204.138', '72.14.204.102', '72.14.204.101'] 
00:58 test INFO: success 

注意挖掘返回['63.251.179.13', '8.15.7.117']爲不存在的網址。

我相信我的ISP正在將不存在的地址更改爲63.251.179.13或8.15.7.117。你的ISP可能會做一些不同的事。在這種情況下,您可能必須將nonexistent更改爲其他內容。