python - Python 中的后台进程

标签 python subprocess multiprocessing popen

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

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/

相关文章:

python - 检查导入模块的路径,不带 __file__

python - 任意形状 NumPy 数组的点积

multithreading - 在 JavaEE 6 中执行子进程

python - python中的多线程网络请求—— 'Name or service not known'

python - python中的调用堆栈是否分别在多线程和多处理中的线程或进程之间共享?

python - 使用多处理保存多个 matplotlib 图形

python - 稀疏矩阵的条件数

python - 以 nohup 启动的进程未与父进程分离

python - 启动应用程序时出现问题 : Last 2 Line's of Script

python - 将字符串转换成字典