简体   繁体   English

在Python多处理中,如何使用队列在进程之间传递用户定义的对象?

[英]In Python multiprocessing, how can a user-defined object be communicated between processes using a queue?

I am beginning to put together a simple multiprocessing job management system and I am having some difficulty in sending a user-defined object (of class Message , shown below) between processes using a queue (the queue communications , shown below). 我开始组合一个简单的多处理作业管理系统,并且在使用队列(如下所示的队列communications )在进程之间发送用户定义的对象( Message类,如下所示)时遇到了一些困难。 Could you point me in the right direction on getting this object (or something similar) sent between processes using a queue? 您能为我指出在使用队列在进程之间发送此对象(或类似对象)的正确方向吗? Feel free to offer other comments critical of any approaches shown in the code. 随意提供其他批评代码中显示的任何方法的注释。

#!/usr/bin/env python

import multiprocessing
from multiprocessing import Queue
import os
import signal
import time

class Message:
    """
    This class acts as a container for process information. The conventions for
    the various member variables are as follows:

    - messageType (specification of message type)
        - "status"
        - "result"
        - "error"
    - sender (name of sender process)
        - str(os.getpid())
        - "janus"
    - recipient (name of recipient process)
        - str(os.getpid())
        - "all"
        - "janus"
    - senderStatus (specification of sender status)
        - "running"
        - "halt"
        - "complete"
        - "waiting"
    - controlMessage (control message for recipient process)
        - "start"
        - "terminate"
        - "report"
        - "pause"
    - resultObject (some object containing results)
        - example: tuple
    - naturalLanguageMessage (natural language message, e.g. human-readable)
        - human readable string
    - timeStamp (message timestamp)
        - time.time()
    """
    messageType="status"
    sender="unknown"
    recipient="all"
    senderStatus="running"
    controlMessage="null"
    resultObject="null"
    naturalLanguageMessage="This is natural language text."
    timeStamp=time.time()
    def set(
        self,
        messageType,
        sender,
        recipient,
        senderStatus,
        controlMessage,
        resultObject,
        naturalLanguageMessage,
        timeStamp=time.time()
        ):
        """
        This function sets the values of the member variables all at once.
        """
        self.messageType=messageType
        self.sender=sender
        self.recipient=recipient
        self.senderStatus=senderStatus
        self.controlMessage=controlMessage
        self.resultObject=resultObject
        self.naturalLanguageMessage=naturalLanguageMessage
        def timeStamp(self):
            # Update the timestamp in the timestamp member variable.
            self.timeStamp=time.time()
        def printout(self):
            # Print a dictionary of all member variables.
            #print('-'*80)
            #print("message content:")
            printHR(vars(self))
            #print('-'*80)
def printHR(object):
    """
    This function prints a specified object in a human readable way.
    """
    # dictionary
    if isinstance(object, dict):
        for key, value in sorted(object.items()):
            print u'{0}: {1}'.format(key, value)
    # list or tuple
    elif isinstance(object, list) or isinstance(object, tuple):
        for element in object:
            print element
    # other
    else:
        print object

def initialise_process():
    signal.signal(signal.SIGINT, signal.SIG_IGN)

def work1():
    processID=os.getpid()
    time.sleep(3)
    print "  work function: work run by process number %d" % (os.getpid())
    # prepare message
    message=Message()
    message.set(
        "status",
        str(processID),
        "janus",
        "running",
        "null",
        "null",
        "work running"
    )
    # send message
    communications.put(message)

def workFunctionTest(testString):
    processID=os.getpid()
    print("test string:")
    print(testString)
    # prepare message
    message=Message()
    message.set(
            "status",
            str(processID),
            "janus",
            "running",
            "null",
            "null",
            "work running")
    # send message
    communications.put(message)
    # do work
    time.sleep(3)

def janus(
    workFunction=workFunctionTest,
    numberOfJobs=1,
    numberOfProcesses=4
    ):
    # printout of multiprocessing specifications
    print("\nJANUS MULTIPROCESSING JOB SYSTEM\n")
    print("  multiprocessing specifications:")
    print("    number of jobs: %s" % (str(numberOfJobs)))
    print("    number of processes: %s" % (str(numberOfProcesses)))
    print("    work to complete: %s" % (str(workFunction)))
    #print("    arguments for work function: " %s (str(workFunctionArguments)))

    # create process pool
    print("  initialising process pool...")
    pool1 = multiprocessing.Pool(numberOfProcesses, initialise_process)
    print("    pool created: %s" % (str(pool1)))

    # create message queue for interprocess communications
    print("  initialising interprocess communications queue...")
    communications=Queue()
    print("    queue created: %s" % (str(communications)))

    # send work to pool
    print("  applying work to pool...")
    print("    applying each of %s jobs," % (str(numberOfJobs)))
    for jobIndex in range(numberOfJobs):
        print("      applying work function %s as job %s..."
            % (str(workFunction), jobIndex))
        pool1.apply_async(workFunction)

    # monitor processes

    # check messages
    while True:
        time.sleep(3)
        if communications.empty() == True:
            print("  checking for messages... no messages")
        elif communications.empty() == False:
            buffer=communications.get()
        print('-'*80)
            print("new message:")
            print buffer
        print('-'*80)
            break
        else:
            print("    fail")
    # monitor
    try:
        print "  jobs running..."
        time.sleep(10)
    except KeyboardInterrupt:
        print "  termination command received\nterminating processes..."
        pool1.terminate()
        pool1.join()
    else:
        print "  jobs complete\nterminating..."
        pool1.close()
        pool1.join()

def main():
    print('-'*80)
    janus(work1, 5)
    print '-'*80

if __name__ == "__main__":
    main()

check out python celery project 签出python celery项目

Celery is an asynchronous task queue/job queue based on distributed message passing. Celery是基于分布式消息传递的异步任务队列/作业队列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在子流程之间传递用户定义的对象 - Passing a user-defined object between sub-processes 在不使用多处理模块的情况下在Python进程之间排队 - Queue between Python processes without using the multiprocessing module 如何在python中的用户定义搜索字符串中支持*? - How can I support * in user-defined search strings in python? Python 中的用户定义 class 是 object 本身吗? - Is a user-defined class in Python an object itself? 在从python对象继承的Class和从另一个用户定义的Class继承的Class上使用super()之间的区别是什么 - What's the difference between using super() on a Class inherited from python object and a Class inherited from another user-defined Class 是否可以从python多处理模块的进程之间自动共享队列对象? - Is queue object automatically shared among Processes from python multiprocessing module? 如何在Python的进程之间共享队列? - How can I share a Queue between processes in Python? 对用户定义的类列表进行多处理? - Multiprocessing on a list of user-defined classes? 使用 python 如何使用队列在子进程和主进程之间传递数据? - Using python how can I pass data between child and main processes with Queue? 如何在python中绘制用户定义的分布? - How to draw on a user-defined distribution in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM