Python中如何将数组存储的参数传入函数调用并获取返回值
Python 动态传递参数调用函数并获取返回值的解决方案
直接使用Python原生的参数解包语法即可实现需求,无需使用exec拼接代码,也不需要依赖多线程,完全兼容可变位置参数、可选关键字参数,也不需要修改原函数源代码。
1. 仅传递位置参数
如果你的参数都存储在列表中,直接用*对列表做解包即可:
def function(a, b, c): return a + b + c target = function args = [1, 2, 3] # * 会把列表内的元素按顺序作为位置参数传入函数 output = target(*args) print(output) # 输出6
2. 同时传递位置参数+关键字参数
如果存在可选关键字参数,可以把关键字参数存储在字典中,搭配**做字典解包使用:
def function(a, b, c=10, d=20): return a + b + c + d target = function args = [1, 2] kwargs = {"c": 30, "d": 40} # 同时解包位置参数和关键字参数 output = target(*args, **kwargs) print(output) # 输出1+2+30+40=73
不推荐exec方案的原因
你当前想到的exec拼接字符串执行的方案存在很多问题:
- exec执行代码默认返回None,你写的
output = exec(...)根本无法拿到原函数的返回值 - 字符串拼接逻辑非常脆弱,如果参数是字符串、自定义对象、包含特殊字符,拼接出来的代码会直接报错
- 存在代码注入风险,如果参数来源不可控,会触发严重的安全问题
多线程场景下获取返回值的方案
如果你确实需要用多线程调用,又需要拿到返回值,可以用concurrent.futures.ThreadPoolExecutor实现:
from concurrent.futures import ThreadPoolExecutor target = function args = [1,2] kwargs = {"c":30, "d":40} with ThreadPoolExecutor(max_workers=1) as executor: # 提交任务,自动解包参数 future = executor.submit(target, *args, **kwargs) # 阻塞等待线程执行完成,拿到返回值 output = future.result()
内容的提问来源于stack exchange,提问作者teodoroven
相关产品推荐
相关产品推荐

