发生错误时自动重启程序

jac*_*ack 3 python restart

该计划是这样的:

HEADER CODE
urllib2.initialization()
try:
    while True:
        urllib2.read(somebytes)
        urllib2.read(somebytes)
        urllib2.read(somebytes)
        ...
except Exception, e:
    print e
FOOTER CODE
Run Code Online (Sandbox Code Playgroud)

我的问题是何时发生错误(超时,由对等方重置连接等),如何从urllib2.initialization()而不是现有的主程序重新启动并再次从HEADER CODE重新启动?

unu*_*tbu 5

您可以将代码包装在"while not done"循环中:

#!/usr/bin/env python

HEADER CODE
done=False
while not done:
    try:
        urllib2.initialization()
        while True:
            # I assume you have code to break out of this loop
            urllib2.read(somebytes)
            urllib2.read(somebytes)
            urllib2.read(somebytes)
            ...
    except Exception, e:    # Try to be more specific about the execeptions 
                            # you wish to catch here
        print e
    else:
    # This block is only executed if the try-block executes without
    # raising an exception
        done=True
FOOTER CODE
Run Code Online (Sandbox Code Playgroud)