2012-02-14 12 views
1

[OK]をみんな、私はPythonのurllib2のタイムアウト

ここ....グーグルで検索してきたし、ここstackoverflowの中でこの答えのために、数時間後にこれを行うための作業スクリプトの正解を見ていない私pasteには、ソケットやタイムアウトパラメータでタイムアウトが設定された存在しないURLのデフォルトのタイムアウトを設定するPythonの作業スクリプトが4つあります。

タイムアウトが発生しないように、誰も動作しません。

アイデア?

まずexmaple:

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

+0

ありがとう@unutbuしかし、これはタイムアウトの問題に関連しない別の状況です。彼女は悪い場所を送るときに彼女がどのように200になっているのか知りたい。 – dyoser

答えて

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

+0

@dyoser、明示的にプロトコルhttp://を指定することを忘れないでください。あなたの 'http:// faluquito.com/equipo.php'に接続しようとしました。それは常に約10秒かかる、私は問題がドメイン名の解決であると思う接続は、ブロッキングOSのルーチンに委任され、コントロールがPythonの側にある直後に終了するようです。私は間違っているかもしれません。 – newtover

+0

これは編集者がそれを表示しなかったためです:)しかし、そこには(http:// wwwという意味です)..はい、タイムアウトが役に立たない場合があるようです – dyoser

1

あなたのマシンは、UNIXプログラムの発掘を持っている場合、あなたはこのような、存在しないURLを識別することができる場合があります私のマシン上で

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 

ていることに注意してくださいdigは、存在しないURLの場合は['63.251.179.13', '8.15.7.117']を返します。

ISPが存在しないアドレスを63.251.179.13または8.15.7.117に変更していると思います。あなたのISPは何か違うことをするかもしれません。その場合はnonexistentを別のものに変更する必要があります。

関連する問題