【问题标题】:Developing a basic command line utility to control another process [closed]开发一个基本的命令行实用程序来控制另一个进程[关闭]
【发布时间】:2021-04-04 09:57:57
【问题描述】:

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

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

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

【问题讨论】:

    标签: python process multiprocessing client-server


    【解决方案1】:

    服务器.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
    

    客户端.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")
    

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

    这里有一点教程:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      相关资源
      最近更新 更多