【问题标题】:Python socket.timeoutPython socket.timeout
【发布时间】:2016-07-24 07:51:22
【问题描述】:

我在启动时运行一个脚本,并且每一秒都用 Python 编写。它可以在有限的时间内正常工作(似乎变化约 5/10 分钟),然后产生以下错误。

我没有尝试更改睡眠时间,因为这是一个“测试”脚本,但我将使用必须每秒运行一次的脚本,因此试图找到正确的方法。

谷歌似乎在答案方面几乎没有产生什么,也许我使用了错误的术语,但我不确定它的睡眠时间是否可能是 ping IP 失败?

Python

import time, urllib2

def internet_on():
    try:
        response=urllib2.urlopen('http://64.233.160.94',timeout=1)
        return '<img class="right" src="networkon.png" width="32" height="32">'
    except urllib2.URLError as err: pass
    return '<img class="right" src="networkoff.png" width="32" height="32">'

output = internet_on()    
f = open('/var/www/html/viv/wifiout.html', 'w')
print >> f, output
f.close()

time.sleep(1)

while True:
    internet_on()

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Vivarium Enviroment Control Centre</title>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
    function updateTime() {
        var currentTime = new Date();
        var hours = currentTime.getHours();
        var minutes = currentTime.getMinutes();
        var seconds = currentTime.getSeconds();
        if (minutes < 10){
            minutes = "0" + minutes;
        }
        if (seconds < 10){
            seconds = "0" + seconds;
        }
        var v = hours + ":" + minutes + ":" + seconds + " ";
        if(hours > 11){
            v+="PM";
        } else {
            v+="AM"
        }
        setTimeout("updateTime()",1000);
        document.getElementById('time').innerHTML=v;
    }

  $("document").ready(function(){
        updateTime();

        setInterval(function(){
          $("#wifi").load('wifiout.html');
        },1000);
      });

function changeStatus() {
    var image = document.getElementById('lightStatus');
    if (image.src.match("lightoff")) {
        image.src = "lighton.png";
    } else {
        image.src = "lightoff.png";
    }
}
</script>
</head>
<body>
<div id="topbar">
    <span id="time"></span>
    <span id="wifi"></span>
    <img id="lightStatus" class="right" onclick="changeStatus()" src="lightoff.png" width="32" height="32">
</div>
</body>
</html>

运行一段时间后抛出的错误

pi@Vivarium:~ $ sudo python /home/pi/Desktop/wifi.py
Traceback (most recent call last):
  File "/home/pi/Desktop/wifi.py", line 17, in <module>
    internet_on()
  File "/home/pi/Desktop/wifi.py", line 8, in internet_on
    urllib2.urlopen('http://64.233.160.94',timeout=1)
  File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 437, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 550, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 469, in error
    result = self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 656, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/usr/lib/python2.7/urllib2.py", line 437, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 550, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 469, in error
    result = self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 656, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/usr/lib/python2.7/urllib2.py", line 431, in open
    response = self._open(req, data)
  File "/usr/lib/python2.7/urllib2.py", line 449, in _open
    '_open', req)
  File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 1227, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/usr/lib/python2.7/urllib2.py", line 1200, in do_open
    r = h.getresponse(buffering=True)
  File "/usr/lib/python2.7/httplib.py", line 1073, in getresponse
    response.begin()
  File "/usr/lib/python2.7/httplib.py", line 415, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python2.7/httplib.py", line 371, in _read_status
    line = self.fp.readline(_MAXLINE + 1)
  File "/usr/lib/python2.7/socket.py", line 476, in readline
    data = self._sock.recv(self._rbufsize)
socket.timeout: timed out

【问题讨论】:

  • 您的问题似乎与缺乏连接有关,这可能是以下两个问题之一:代理或目标服务器缺乏响应。第一个问题与 python 中的脚本不使用机器上的凭据有关,因此,如果您在途中有代理,它将不会进行身份验证并给出错误。
  • 没有代理设置或使用所以目标服务器问题。原因是什么?那是谷歌的 IP,所以我使用它时假设它不会因为谷歌的规模而引起问题。
  • 那么,您完全确定您使用的网络不需要代理吗?因为这是企业网络中非常常见的问题。
  • 我在家。但我确实在工作和家庭中遇到了同样的问题和时间安排。
  • 您是否意识到您提供的 python 脚本使用该函数返回的单个 &lt;img&gt; 标记覆盖了您的 html 文件,然后不断尝试检索数据,直到实际检索需要超过一秒钟数据?您几乎肯定会给网络连接带来巨大压力,这很可能需要一秒钟以上,因为服务器需要一些时间来刷新一些捕获,internet_on() 在 while 循环中运行多少次才会给您错误?

标签: python python-2.7 timeout urllib2


【解决方案1】:

试试这个:

import time, urllib2

def internet_on():
    returnValue = '<img class="right" src="networkon.png" width="32" height="32">'
    try:
        response=urllib2.urlopen('http://64.233.160.94',timeout=1)
    except:
        returnValue = '<img class="right" src="networkoff.png" width="32" height="32">'
    return returnValue


while True:
    output = internet_on()
    with open('/var/www/html/viv/wifiout.html', 'w') as f:
        f.write(output)
    time.sleep(5)

【讨论】:

  • time.sleep 接受一个以秒为单位的参数,你为什么要等待 1000 秒?
  • 看起来像 JQuery 1000 嗯?哈好吧让我试试看。
  • 我只设置了 5 秒,这应该是网络在连接之间稍作喘息的好时机。
  • @Walter_Ritzel 脚本正在运行!不幸的是,请稍等片刻,然后单击对勾。然后让它过夜,看看它是否还在运行,但就像你说的,5 秒就足够了。谢谢。
  • @Walter_Ritzel 我一直在测试一些丢失/加入网络的方法,我发现如果在启动时由 root 运行脚本时没有网络,它似乎不再正确运行脚本.我可以使用我自己的脚本来改变睡眠时间吗?
猜你喜欢
  • 1970-01-01
  • 2017-04-11
  • 2015-02-17
  • 1970-01-01
  • 2021-10-14
  • 2021-05-10
  • 1970-01-01
  • 2015-04-19
  • 1970-01-01
相关资源
最近更新 更多