2017-03-20 45 views
2

我是新来的python和我的脚本持续约3-4小时,并没有保存错误消息。什么可能导致这个问题?我的python脚本停止工作,没有任何干预

这里是我的代码:

import time 
import urllib.request 
import threading 

def load(): 
    try: 
     content = str(urllib.request.urlopen("[URL]").read()) 
     # do sth with content 
     threading.Timer(0.5, load).start() 
    except Exception as e: 
     file = open("Error.txt","w") 
     file.write(time.strftime("%H:%M:%S\n\n")) 
     file.write(e.message) 
     file.close() 
     threading.Timer(0.5, load).start() 

def main(args): 
    load() 
    return 0 

if __name__ == '__main__': 
    import sys 
    sys.exit(main(sys.argv)) 

这里是在Ubuntu 14.04 nohup.out文件中:

Exception in thread Thread-907: 
Traceback (most recent call last): 
    File "/usr/lib/python3.4/urllib/request.py", line 1182, in do_open 
    h.request(req.get_method(), req.selector, req.data, headers) 
    File "/usr/lib/python3.4/http/client.py", line 1125, in request 
    self._send_request(method, url, body, headers) 
    File "/usr/lib/python3.4/http/client.py", line 1163, in _send_request 
    self.endheaders(body) 
    File "/usr/lib/python3.4/http/client.py", line 1121, in endheaders 
    self._send_output(message_body) 
    File "/usr/lib/python3.4/http/client.py", line 951, in _send_output 
    self.send(msg) 
    File "/usr/lib/python3.4/http/client.py", line 886, in send 
    self.connect() 
    File "/usr/lib/python3.4/http/client.py", line 863, in connect 
    self.timeout, self.source_address) 
    File "/usr/lib/python3.4/socket.py", line 512, in create_connection 
    raise err 
    File "/usr/lib/python3.4/socket.py", line 503, in create_connection 
    sock.connect(sa) 
OSError: [Errno 101] Network is unreachable 
+2

'Expection' - >'Exception'。错字,请关闭。 – njzk2

+0

请将file = open(“Error.txt”,“w”)更改为file = open(“Error.txt”,“a”)模式。 – Varad

+0

'日志记录'模块比手动打开文件更有意义 –

回答

0

Network is unreachable通常意味着你有你的计算机上的连接问题。也许这是一个间歇性的,短暂的问题,但你永远不会尝试检测它并从中恢复。

考虑使用类似retry decorator的东西,或手动处理它。

(我也找到你的循环提取逻辑相当奇特为什么一个简单的单线程循环没有为你工作的方式?)