0

Consider the following python code:

Status = 1
while Status == 1:
  print("Program is Running")
else:
    print("Program is not Running")

I want to be able to run a command in a different (bash) terminal that changes the variable Status.

I have looked at similar questions on the website, but they assume that you get input from where you run the program.

I have seen this be applied in scenarios as:

  1. Run the program in one terminal

  2. Open the second and write

    pathtocode/code.py toggle
    

which stops the program.

If anybody could help me with this I would greatly appreciate it.

Maths Wizzard
  • 221
  • 1
  • 6
  • 1
    https://docs.python.org/3/library/multiprocessing.shared_memory.html – rasjani Sep 28 '22 at 10:20
  • Are you specifically looking for a way to terminate a program? Because in that case you may want to look at termination signals instead, see for example https://stackoverflow.com/questions/18499497/how-to-process-sigterm-signal-gracefully – Johan Sep 28 '22 at 10:26
  • @Johan, not really. Ideally, I would want it constantly output "Program is running" or "Program is not running". Something that seems to have this capability is https://github.com/unode/polypomo/blob/master/polypomo, however, I do not understand what is done there. – Maths Wizzard Sep 28 '22 at 10:28

1 Answers1

1

One option is to use a socket. Here is an example (you have to install click)

import click

import socket


HOST = "127.0.0.1"  # Standard loopback interface address (localhost)
PORT = 65431  # Port to listen on (non-privileged ports are > 1023)
BUFFER_SIZE = 1024

@click.group(chain=True)
def cli():
    pass


@cli.command()
def main():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        s.listen()
        conn, addr = s.accept()
        with conn:
            print(f"Connected by {addr}")
            while True:
                data = conn.recv(BUFFER_SIZE)
                if not data:
                    break
                if data.decode() == "1":
                    print("Program is not Running")


@cli.command()
def toggle():
    clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    clientSocket.connect((HOST, PORT))
    data = "1"
    clientSocket.send(data.encode())


if __name__ == "__main__":
    cli()

Then you can run:

python pathtocode/code.py main

and

python pathtocode/code.py toggle

Another option could be to write to a text file.

Tom McLean
  • 5,583
  • 1
  • 11
  • 36
  • Hi, thanks for the answer. Apologies for my programing illiteracy but I need some help understanding the answer. Could you possibly explain what each block does? Moreover, when would one put arguments for when the program is running (i.e. before toggle as been executed)? – Maths Wizzard Sep 28 '22 at 10:42