gpt4 book ai didi

python - Python 中的后台进程

转载 作者:太空狗 更新时间:2023-10-30 02:49:39 25 4
gpt4 key购买 nike

我需要创建一个后台进程来等待传入的命令并执行它们。这是代码:

instance_tuple.popen = subprocess.Popen(['python',\
os.path.join(config['scripts_dir'],\
'instance_script.py')],\
stdin = subprocess.PIPE,\
stdout = subprocess.PIPE)

进程函数代码:

if __name__ == '__main__':
config = dict()
is_config_valid = False
print 'Hello from instance process'
while True:
cmd_str = raw_input()
if (cmd_str.strip() != ''):
print 'received %s' % cmd_str
command = json.loads(cmd_str)
print 'received command: %s' % str(command)
sys.stdout.flush()
if command['name'] == 'set_variable':
name = command['args'][0]
value = command['args'][1]
config[name] = value
is_config_valid = validate_instance_dict(config)
elif is_config_valid:
if (command['name'] == 'init_model'):
config['instance'].init_model()
elif (command['name'] == 'get_tree'):
tree = config['instance'].get_fidesys_tree(command['args'])
result = CommandResult(command.name, tree)
print 'process exit'

这就是我向流程发送数据的方式:第一次测试运行正常:

(input, errors) = instance_tuple.popen \
.communicate(json.dumps({'name': 'name', 'args': list()}))

稍后由于某些原因 raw_input() 得到一个 EOF 并且进程退出。设置进程间通信的正确方法是什么?

最佳答案

我喜欢用zeromq为了这。我使用 zmq.PULL 套接字设置服务器,该套接字监听使用 zmq.PUSH 套接字发送消息的客户端。真的很容易使用:

import zmq

def client(msg)
context = zmq.Context()
client = context.socket(zmq.PUSH)
client.connect('tcp://127.0.0.1:9999')
client.send(msg)

def server():
context = zmq.Context()
server = context.socket(zmq.PULL)
server.bind('tcp://127.0.0.1:9999')

while True:
msg = server.recv()
..do something with each message

if __name__ == '__main__': server()

关于python - Python 中的后台进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7174478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com