[英]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.