繁体   English   中英

Python Executor - 以参数作为参数传递函数

[英]Python Executor - Passing function with argument as argument

我的目标是创建一个函数,我可以用它来衡量另一个函数的执行和资源使用情况。 使用教程,我使用 Python 的 ThreadPoolExecutor 创建了以下内容:

from resource import *
from time import sleep
from concurrent.futures import ThreadPoolExecutor

class MemoryMonitor:
    def __init__(self):
        self.keep_measuring = True

    def measure_usage(self):
        max_usage = 0
        u_run_time = 0
        s_run_time = 0
        while self.keep_measuring:
            max_usage = max(max_usage, getrusage(RUSAGE_SELF).ru_maxrss)
            u_run_time = max(u_run_time, getrusage(RUSAGE_SELF).ru_utime) 
            s_run_time = max(s_run_time, getrusage(RUSAGE_SELF).ru_stime) 
        sleep(0.1) # run this loop every 0.1 seconds
        return [max_usage, u_run_time, s_run_time]

def execute(function):
    with ThreadPoolExecutor() as executor:
        monitor = MemoryMonitor()
        stats_thread = executor.submit(monitor.measure_usage)
        try:
            fn_thread = executor.submit(function)
            result = fn_thread.result()
            print("print result")
            print(result)
            print("print result type")
            print(type(result))
        finally:
            monitor.keep_measuring = False
            stats = stats_thread.result()
        print(stats)
        return result

def foo():
    i = 0
    while i < 3:
        print("foo")
        i+=1
    return 1

def bar(x):
    while x < 3:
        print("foobar")
        x+=1
    return 1

var = execute(foo)
print("Var = " + str(var))
var = execute(bar(0))
print("Var = " + str(var))

如果我将函数foo作为参数传递给函数execute ,它会打印正确的结果并返回 foo 返回的值。

如果我以相同的方式传递函数bar ,但 bar 本身需要一个参数,则该函数将运行(打印 3 次),然后出现以下错误:

result = self.fn(*self.args, **self.kwargs)
TypeError: 'int' object is not callable

经过一些测试,如果该函数本身需要一个参数,我被卡住的部分似乎将一个函数作为参数传递。 按照我对ThreadPoolExecutor的理解, fn_thread对象封装了提交的函数的执行。 结果对象应该简单地保存该执行的结果 - 我错过了什么,无法处理传递带有参数的函数?

您正在提交

bar(0) 

代替

bar, 0

为了澄清,请查看提交的签名: submit(fn, *args, **kwargs)

的结果

bar(0)

是一个整数,并且执行程序不能调用一个整数,因为它不是“可调用的”,正如错误消息所暗示的那样。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM