0

I am running a small python code background.py as follows:

class Background:
    def __init__(self):
        self.q = 0

    def run(self):
        while True:
            print(f"test, q={self.q}")
            time.sleep(5)

    def setq(self, x):
        self.q += x
        print(f"New value q={q}")


if __name__ == "__main__":
    bg = Background()
    bg.run()

and I want to start a small python code in another terminal to access this running python code and to execute the method setq so that the value in the running code is being changed. How can this be done easiest?

Alex
  • 41,580
  • 88
  • 260
  • 469
  • 2
    To accomplish this, you should look into using IPC methods like RPC, message passing – pavi2410 May 07 '23 at 12:36
  • Does this answer your question? [Interprocess communication in Python](https://stackoverflow.com/questions/6920858/interprocess-communication-in-python) – luk2302 May 07 '23 at 12:56
  • @pavi2410 I'd appreciate if you could provide a simple, easy, and simple example following my code above. It is not even totally important to actually send data to the running process, just to "notify" the process is fine (as the process can check in a database for the data...) – Alex May 07 '23 at 12:56
  • @luk2302 I saw the exact same question and I am asking a different question. The solution in the question you linked here is running an infinite loop looking for data received on the socket. That is actually not what I want. I want a method be executed, if possible. However, the socket implementation COULD be a solution, I just need to replace `time.sleep(5)` with a while loop reading the socket all the time. Not sure if that would be an efficient solution or a waste of resources ... – Alex May 07 '23 at 12:58
  • 1
    Additionally https://docs.python.org/3/library/ipc.html - there are many ways to achieve what you are looking for. – luk2302 May 07 '23 at 13:00

0 Answers0