Warm tip: This article is reproduced from serverfault.com, please click

Developing a basic command line utility to control another process

发布于 2020-12-27 08:05:45

I'm trying to develop a simple application in Python using multiprocessing & client server architectures.

I'm trying to achieve a process which does its thing in the background, and another script which will connect to it and control its behaviour. For example tell it to pause what it is doing, or doing something else entirely, or stop it altogether.

What are the possible ways / architectures to achieve this functionality? For example, can I create a process with python and then create another script to get a reference to it through its PID and communicate?

Questioner
SercioSoydanov
Viewed
0
xcodz-dot 2020-12-27 16:52:37

Server.py

from threading import Thread
import socket
import pickle

server_configuration = {
    "status": "start",
    "delay": 1
}  # Server Configuration

def server():
    address = ("localhost", 4000)
    server_socket = socket.socket()  # Create a network object
    server_socket.bind(address)  # Start server on the address
    server_socket.listen(5)  # start accepting requests and allow maximum 5 requests in the request buffer
    while True:
        connection, client_address = server_socket.accept()  # Accept a connection
        request = connection.recv(10000)  # recv maximum 10 KB of requested data
        request = pickle.loads(request)  # load the request
        
        # Check the request
        if request["type"] = "stop":
            server_configuration["status"] = "stop"
        elif request["type"] = "start":
            server_configuration["status"] = "start"
        elif request["type"] = "set_delay":
            server_configuration["delay"] = request["time"]
        connection.close()


def background_task():  # You can do any task here
    from time import sleep
    count = 0  
    while True:
        if server_configuration["status"] == "start":
            print(count)
            count += 1
            time.sleep(server_configuration["delay"])


if __name__ == "__main__":
    back_ground_thread = Thread(target=background_task)  # Make a thread
    back_ground_thread.start()  # Start the thread
    server()  # start the server

Client.py

import socket
import pickle


def make_request(name: str, **kwargs):
    return pickle.dumps({"type": name, **kwargs})


def send_request(request):
    address = ("localhost", 4000)
    client = socket.socket()
    client.connect(address)
    client.sendall(request)
    client.close()


while True:
    print("\nCommands: set_delay, stop, start")
    command = input(">").split()
    if len(command) == 0:  # If command == []
        pass
    elif command[0] == "start":
        request = make_request("start")
        send_request(request)
    elif command[0] == "stop":
        request = make_request("stop")
        send_request(request)
    elif command[0] == "set_delay" and len(command) > 1:
        request = make_request("start", delay=int(command[1]))
        send_request(request)
    else:
        print("Invalid Request")

Now you can try to study the above codes. Also please run server.py first and then client.py in another terminal. you can see that behaviour of server changes when client sends request to server.

Here is a little bit of tutorial: