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



我正在尝试使用多处理&客户端-服务器体系结构。

我正在努力实现一个在后台完成任务的过程,以及另一个连接到它并控制其行为的脚本。例如,告诉它暂停正在做的事情,或者完全停止做其他事情。

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

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

客户端.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。您可以看到,当客户端向服务器发送请求时,服务器的行为会发生变化。

以下是一些教程:

  • 插座
  • 泡菜
  • 螺纹

相关内容

  • 没有找到相关文章

最新更新