在Python2.6上处理异常的正确方法

时间:2018-05-23 09:55:15

标签: python urllib2 python-2.6

我有一个连续运行的Python脚本。如果目录上有任何新文件,那么python将使用urllib2打开url来对特定的ip做一些请求。

这是代码

encoded_string = base64.b64encode(image_file.read())
values = dumps({
    'image_data':encoded_string,
    'requestCode':'111'
})

headers = {"Content-Type": "application/json"}
request = Request("http:/xx.xxx.xx.xxx/api/carplate_service",data=values, headers=headers)
response = urlopen(request, timeout=60)

代码运行良好但是在随机时间,假设通常发生在上午1-2点,然后我收到此错误:

<class 'urllib2.URLError'> - <urlopen error [Errno 110] Connection timed out>

我对这个函数有一个例外:

try:
    ip = sys.argv[1]
    histId = int(sys.argv[2])
    handler = ModHandler()
    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm, handler)
    wdd = wm.add_watch('./' + ip + '/', pyinotify.IN_CLOSE_WRITE)
    notifier.loop()
except BaseException as e:
    with open("error.log", "a") as text_file:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        text_file.write( time.strftime("%Y-%m-%d %H:%M:%S") + " [" + str(exc_tb.tb_lineno) + " - " + fname + "] : " + str(exc_type) + " - " +  str(e) + "\n")
        text_file.close();

异常不能正常工作,因为如果出现上述错误,应用程序无法继续。

我的问题是如何使程序仍然继续甚至抛出异常?

我正在使用python2.6

由于

1 个答案:

答案 0 :(得分:0)

对于外部服务的函数调用,我通常会发现以下基本结构运行良好

import time

expire_time = 2

while True:
    start_time = time.time()
    try:
        ip = sys.argv[1]
        histId = int(sys.argv[2])
        handler = ModHandler()
        wm = pyinotify.WatchManager()
        notifier = pyinotify.Notifier(wm, handler)
        wdd = wm.add_watch('./' + ip + '/', pyinotify.IN_CLOSE_WRITE)
        notifier.loop()
        break
    except BaseException as e:
        now_time = time.time()
        if now_time > start_time + expire_time:
            raise e
        else:
            with open("error.log", "a") as text_file:
                exc_type, exc_obj, exc_tb = sys.exc_info()
                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                text_file.write( time.strftime("%Y-%m-%d %H:%M:%S") + " [" + str(exc_tb.tb_lineno) + " - " + fname + "] : " + str(exc_type) + " - " +  str(e) + "\n")
                text_file.close();

使用您提供的代码可能看起来像这样

viewModel = ViewModelProviders.of(activity!!).get(BookmarkViewModel::class.java)