我创建了一个连接到websocket并通过数据流传输数据的脚本。现在我试图找到一种方法来使用try,除非在流断开连接或错误输出时重新连接到websocket。如果重新连接尝试超过脚本退出的三倍。我尝试按照下面显示的方式进行操作,但它不起作用。有没有其他方法可以尝试重新连接而不是使用try和except?
#!python
from websocket import create_connection
LINK='wss://ws-feed.somestream.com'
MAX_ATTEMPTS = 3 #Max attempts before exiting
attempts = 0 #number of retries
def getStream(LINK):
ws = create_connection(LINK)
while True:
print ws.recv()
try:
getStream(LINK)
except:
print "connection error"
attempts = attempts + 1
if attempts < 3:
getStream(LINK)
答案 0 :(得分:1)
这会有用吗?
try:
...
except:
attempt = 1
while attempt <=3:
print "connection error"
try:
getStream(LINK)
attempt = 4
except:
attempt += 1