1

I am running a python script that subscribe to a websocket feed, I would like to have the script to be started (a new instance ) when a certain event in the code is triggered, in my case a disconnection from the server.

my python file code :

class Client:
    
    def __init__(self, client_id, qties, on_data):
        self.responses = []
        headers = self.create_headers(self.api_key, self.secret_key, self.passphrase)

        socketio_client = socketio.Client()

        @socketio_client.on('disconnect', namespace='/streaming')
        def on_disconnect():
            print('Server disconnected.')
            quit()
               ^^^^

        @socketio_client.on('connect_error', namespace='/streaming')
        def on_connect_error(msg):
            print(f'Cannot connect to the server. Error: {msg}')
            quit()


        @socketio_client.on('stream',namespace='/streaming')
        def on_price(res):
            on_data(res)
            print(f"Response from Client {client_id} @ {time.time()}")

...

I would like to replace the quit() on on_disconnect() by some code that runs the file from the begining.

jaquemus
  • 33
  • 5

1 Answers1

1
import os 
import sys
if sys.platform == "win32":
    os.system(f'start cmd /k py {__file__}')
else:
    os.system(f'python3 {__file__} &')
exit()
Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
  • Ok so I need to add this code in the beginning of the script then invoke it ? – jaquemus Apr 14 '22 at 18:15
  • 1
    Replace quit() with this. add the imports at top. – Smart Manoj Apr 15 '22 at 02:39
  • `OSError: [Errno 98] Address already in use` Autorestart fails because the port is already in use by the crashed process, any idea on how to bypass this ? – jaquemus Apr 21 '22 at 03:15
  • 1
    Add `socketio_client.disconnect()` before `quit` – Smart Manoj Apr 21 '22 at 04:22
  • somehow it doesn't work, I think I need to force address re-use, for reference : https://stackoverflow.com/a/4466035/14585149 unsure how to adapt this in my code `sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)` – jaquemus Apr 26 '22 at 16:00
  • Could you add full traceback? – Smart Manoj Apr 28 '22 at 05:09
  • turns out my script has a server and that's what's causing the error, at the end of my script file I have this : `server = SimpleSSLWebSocketServer('127.0.0.1', 7777, Server, './c.pem', './k.pem', ssl.PROTOCOL_TLSv1_2)` `server.serveforever()`, I think i need to close the connection on this server, trying to figure out how. – jaquemus Apr 28 '22 at 14:03
  • Separate the server and client in two programs – Smart Manoj Apr 30 '22 at 10:08