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

python-开发基本的命令行实用程序以控制另一个进程

(python - Developing a basic command line utility to control another process)

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

我正在尝试使用多处理和客户端服务器体系结构在Python中开发一个简单的应用程序。

我正在尝试实现一个在后台执行其工作的进程,以及另一个将与其连接并控制其行为的脚本。例如,告诉它暂停正在执行的操作,或者完全停止执行其他操作,或者完全停止它。

实现此功能的可能方法/体系结构是什么?例如,我可以使用python创建一个进程,然后创建另一个脚本以通过其PID获取对它的引用并进行通信吗?

Questioner
SercioSoydanov
Viewed
11
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

客户端

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")

现在,你可以尝试研究以上代码。另外,请先运行server.py,然后再client.py在另一个终端上运行。你可以看到,当客户端向服务器发送请求时,服务器的行为发生了变化。

这里是一些教程: