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

2024-06-02 11:09:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

#!/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

^{pr2}$

这里我想传递函数名作为参数之一,类似于t1 = FuncThread(datapath_thread, controller, datapaths.listDatapaths(mylib),"datapaths.log",counter)

^{3}$

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


Tags: importselftargetdatetimeloggingcountsysargs
1条回答
网友
1楼 · 发布于 2024-06-02 11:09:50

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

你已经很接近了,与其传入调用函数的结果,不如传入函数本身

def datapath_thread(ipaddress, test_func, testlogfile, count):
    # ...
    for i in range(count):
        # ...
        try:
            (code, val) = test_func(mylib)
        #...
^{pr2}$

相关问题 更多 >