'How to restart a python script when it crashes but doesn't die?

I have a Python script that needs to be running continuously on a linux server, it connects to a webSocket and retrieve a realtime feed of data.

After a dozens of hours, the script crashes but doesn't exit, it displays an error message about losing connection to the server and I have to manually Ctrl+C and run it again.

I am looking for a way to automatically (instantly) restart the python script once it crashes, how can one achieve this ?

Edit : this is the message I get when the script crashes

Server disconnected.
disconnect handler error
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/engineio/client.py", line 496, in _trigger_event
    return self.handlers[event](*args)
  File "/usr/local/lib/python3.8/dist-packages/socketio/client.py", line 632, in _handle_eio_disconnect
    self._trigger_event('disconnect', namespace=n)
  File "/usr/local/lib/python3.8/dist-packages/socketio/client.py", line 550, in _trigger_event
    return self.handlers[namespace][event](*args)
  File "python_script.py", line 29, in on_disconnect
    quit()
  File "/usr/lib/python3.8/_sitebuiltins.py", line 26, in __call__
    raise SystemExit(code)
SystemExit: None

Here is the on_disconnect class parameter code :

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

I think I may have to call an external script to start a new instance of the python script.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source