简体   繁体   English

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

[英]Correct way to handle exception on Python2.6

I had an Python script that running continuously. 我有一个连续运行的Python脚本。 If there any new file on directory then the python will open url using urllib2 to do some request on specific ip. 如果目录上有任何新文件,则python将使用urllib2打开url以对特定ip进行一些请求。

here are the code 这是代码

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)

The code are working well but on random time, let say usually happened on 1-2 AM then I got this error: 该代码运行良好,但在随机时间运行,可以说通常发生在1-2 AM,然后出现此错误:

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

I had an exception on that function on this bellow : 我在下面的那个函数上有一个例外:

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();

The exception not working well because application cannot continue if there are some error like above. 异常无法正常运行,因为如果出现上述类似错误,应用程序将无法继续运行。

My question are how to make program still continue even the exception throw? 我的问题是如何使程序即使异常抛出仍然继续?

I'm using python2.6 我正在使用python2.6

Thanks 谢谢

For function calls that go out to external services I usually find that the following basic structure works pretty well 对于进行外部服务的函数调用,我通常会发现以下基本结构运行良好

import time

expire_time = 2

while True:
    start_time = time.time()
    try:
        # Do something here
        # ....
        # If you make it to the bottom of the code, break out of the loop
        break
    except BaseException as e:
        # Compare the start_time with the current time
        now_time = time.time()
        if now_time > start_time + expire_time:
            raise e

        # Otherwise try executing the `try` block again

Using the code that you've provided it could look something like this 使用您提供的代码可能看起来像这样

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM