Jun-06-2024, 07:20 AM
(Jun-05-2024, 10:22 PM)sawtooth500 Wrote: This I am fascinated by... how can I connect to my script? If I can send an external signal to it to start termination activities that could work instead of using an input().You could use any kind of server such as a http server or whatever. Here is an example using a rpyc server (remote procedure calls). The main program does some work but it also starts a thread running a server on a port that waits for one connection
# rpycserver.py from threading import Thread, Event import rpyc from rpyc.utils.server import OneShotServer from time import sleep PORT = 18861 STOPPED = Event() class StopService(rpyc.Service): def exposed_stop(self): WORKER.stop() class ServerThread(Thread): def __init__(self): Thread.__init__(self) self.server = OneShotServer(StopService, port=PORT) def run(self): self.server.start() def stop(self): STOPPED.set() self.server.close() if __name__ == "__main__": WORKER = ServerThread() WORKER.start() while True: # This is the program's main loop # It checks now and then if the STOPPED event is set # indicating that the stop_service was invoked from # the outside. # It could also stop programmatically by calling # WORKER.stop() if STOPPED.is_set(): break sleep(2) WORKER.join() print("Running cleanup code")In order to stop the program, I run another program
# stoprpycserver.py import rpyc PORT = 18861 if __name__ == "__main__": c = rpyc.connect("localhost", PORT) try: c.root.stop() except EOFError: pass
Output:λ python paillasse/pf/rpycserver.py &
[1] 5091
λ python paillasse/pf/stoprpycserver.py
λ Running cleanup code
[1]+ Done python paillasse/pf/rpycserver.py
You could add features to the server, such as authentication etc.
« We can solve any problem by introducing an extra level of indirection »