如何将函数和参数放入python队列? [英] how to put a function and arguments into python queue?

查看:39
本文介绍了如何将函数和参数放入python队列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 2 个线程的 python 程序(让我们将它们命名为源"和'目的地' ).源线程有时会向目的地发布消息带有一些参数的线程.比目标线程选择一条消息它必须使用保存在消息中的参数调用相应的函数.

I have a python program with 2 threads ( let's name them 'source' and 'destination' ). Source thread sometimes post a message to destination thread with some arguments. Than destination thread picks a message it must call a corresponding function with aruments saved in message.

此任务可以通过多种方式解决.最简单的是你放一个大的'if...if...if' 在目标线程的消息选择周期中并调用函数根据接收到的消息类型和保存的参数.但是这个将导致大量代码(或大查找表)并添加新的消息/处理程序函数将演变为编写代码的附加步骤消息选择周期.

This task can be solved multiple ways. The easy one is tu put a big 'if...if..if' in destination thread's message pick cycle and call function according to received message type and saved arguments. But this will result in huge amounf of code ( or big lookup table ) and adding new messages / handler function will evolve additonal step to write code in message pick cycle.

由于python将函数视为一流对象并具有元组,因此我想要将函数和参数放在消息中,而不是目标线程选择一条消息,它只是调用保存在消息中的函数,没有任何知道它是什么功能.

Since python treats functions as first-class objects and have tuples, i want to put a function and argumens inside a message, so than destination thread picks a message it just call a functon saved within a message without any knowledge what function it is.

我可以为具有指定数量参数的函数编写代码:

I can write a code for a functions with specified number of arguments:

from Queue import *
from thread import *
from time import *

q = Queue()

def HandleMsg( arg1, arg2 ) :
  print arg1, arg2

def HandleAnotherMsg( arg1, arg2, arg3 ) :
  print arg1, arg2, arg3

def DestinationThread( a ) :
  while True :
    (f, a, b) = q.get()
    f( a, b )

start_new_thread( DestinationThread, ( 0, ) )
print "start"
sleep( 1 )
q.put( (HandleMsg, 1, 2) )
sleep( 1 )
print "stop"

问题是:如何修改代码以便我可以 put() 一个函数队列中有多少个参数?例如 HandleAnotherMsg() ?使用 q.put( (HandleAnotherMsg, 1, 2, 3) ) 将引发编译错误:(

The question is: how to modify a code so i can put() a function with any number of arguments in queue? for example HandleAnotherMsg() ? Using q.put( (HandleAnotherMsg, 1, 2, 3) ) will rise a compilation error :(

推荐答案

很简单:

def DestinationThread( a ) :
  while True :
    items = q.get()
    func = items[0]
    args = items[1:]
    func(*args)

这篇关于如何将函数和参数放入python队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆