简体   繁体   中英

Changing a variable in a running python script

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM