2017-12-30 30 views
0

私はwebsocketに接続し、データをストリームするスクリプトを作成しました。今私はストリームを切断またはエラーが発生した場合にtryとexceptを使ってwebsocketに再接続する方法を見つけようとしています。再接続の試行がスクリプトが終了する3回を超える場合。私はそれを以下のようにしてみましたが、うまくいきません。 tryとexceptを使用する以外の再接続を試みる別の方法はありますか?終了する前に、PythonでWebソケットを使って3回試行する方法はありますか?

#!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) 

答えて

1

これは機能しますか?

try: 
    ... 
except: 
    attempt = 1 
    while attempt <=3: 
     print "connection error" 
     try: 
      getStream(LINK) 
      attempt = 4 
     except: 
      attempt += 1 
関連する問題