如何将函数传递给线程中的元组

时间:2013-09-16 19:15:04

标签: python tuples

我的问题在我的代码中交错:

#!/usr/bin/python

import threading
import logging, logging.handlers
import hpclib
import json
import time
from datetime import datetime
from features import *
import sys


if len(sys.argv) != 3:
    print "Please provide the correct inputs"
        print "Usage: rest_test.py <controllerip> <counter>"
    sys.exit()


controller = sys.argv[1]
counter = int(sys.argv[2])



class FuncThread(threading.Thread):
    def __init__(self, target, *args):
        self._target = target
        self._args = args
        threading.Thread.__init__(self)

    def run(self):
        self._target(*self._args)

def datapath_thread(ipaddress, testlogfile,count):
    #initialize logging system
    testlogger = logging.getLogger("testlogger")
    testlogger.setLevel(logging.DEBUG)
    file = open(testlogfile,'w')
    file.close()
    # This handler writes everything to a file.
    h1 = logging.FileHandler(testlogfile)
    f = logging.Formatter("%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s")
    h1.setFormatter(f)
    h1.setLevel(logging.DEBUG)
    testlogger.addHandler(h1)
    mylib = hpclib.hpclib(ipaddress)
    success_count = 0
    failure_count = 0
    for i in range(count):
        t1=datetime.now()
        try:
            (code, val) = datapaths.listDatapaths(mylib)

我想从下面的帖子中传递此函数datapaths.listDatapaths(mylib)作为参数,例如(code,val)=functionname

            if code == 200:
                success_count +=1
            else:
                testlogger.debug("Return Code other than 200 received with code = %d, value = %s"%(code,val))
                failure_count +=1
        except:
            failure_count += 1
            testlogger.debug ("Unexpected error: %s"%sys.exc_info()[0])
            continue

        t2=datetime.now()
        diff=t2-t1
        testlogger.debug('RETURN code: %d. Time taken in sec = %s,Iteration = %d, Success = %d, Failure = %d'%(code,diff.seconds,i+1,success_count,failure_count))
        time.sleep(1)

    testlogger.removeHandler(h1)

# Passing ipadress of controller and log file name
t1 = FuncThread(datapath_thread, controller, "datapaths.log",counter)

在这里,我想将函数名称作为参数之一传递,例如t1 = FuncThread(datapath_thread, controller, datapaths.listDatapaths(mylib),"datapaths.log",counter)

t1.start()
t1.join()

我有很多函数可以像这样调用,所以想要一个简单的方法来使用多个线程从一个函数调用所有函数

1 个答案:

答案 0 :(得分:2)

首先,FuncThread不是很有用 - FuncThread(func, *args)可以拼写为Thread(target=lambda: func(*args))Thread(target=func, args=args)

你非常接近 - 而不是传递调用函数的结果,传递函数本身

def datapath_thread(ipaddress, test_func, testlogfile, count):
    # ...
    for i in range(count):
        # ...
        try:
            (code, val) = test_func(mylib)
        #...
thread = Thread(target=datapath_thread, args=(
    controller,
    datapaths.listDatapaths,
    "datapaths.log",
    counter
))