【问题标题】:Passing more than one variable to PoolExecutor将多个变量传递给 PoolExecutor
【发布时间】:2020-10-03 05:48:15
【问题描述】:

下面的代码可以运行,但是...

from concurrent.futures import ThreadPoolExecutor as PoolExecutor

date = "2020-06-12"
adjusted_symbol_list = ["AAPL", "MSFT", "NFLX"]
date_variable = get_specific_date_from_web()


def filter_2ndconfirm(symbol):
    if date == "2020-06-12":
        if make_calc() == True:
            print(symbol)

def filter_2ndconfirm_workers(filter_2ndconfirm_workers, adjusted_symbol_list):
    with PoolExecutor(max_workers=5) as executor:
        for _ in executor.map(filter_2ndconfirm_workers, adjusted_symbol_list):
            pass

filter_2ndconfirm_workers(filter_2ndconfirm, adjusted_symbol_list)

get_specific_date_from_web() 在几个 http 连接后进行计算并获取日期,因此应该只工作一次。上面的代码可以工作,但我怎样才能插入另一个变量,我的意思是 date_variable 到 filter_2ndconfirm 函数?我可以像下面这样,但我不想为每个符号查询网络:

def filter_2ndconfirm(symbol):
    date_variable = get_specific_date_from_web()
    if date == date_variable:
        print(symbol)

谢谢

【问题讨论】:

  • 不要在 Python 中得到它,任何时候 API 为您提供存储或传递 one 不透明值的地方,您始终可以提供元组或列表,或字典,或自定义类的实例,等等。

标签: python multithreading parallel-processing threadpool


【解决方案1】:

如果您已经在 filter_2ndconfirm 函数之外定义了变量 date_variable,那么您可以在函数内部访问它的值,因此:

def filter_2ndconfirm(symbol):
    if date == date_variable:
        print(symbol)

但是,这样您将无法在函数内部更改其值。为此,您可以将其用作 全局 变量。

否则,您可以将 date_variable 作为参数传递给函数:

将此新参数添加到 filter_2ndconfirm

def filter_2ndconfirm(symbol, date_variable):
    if date == date_variable:
        print(symbol)
    if date == "2020-06-12":
        if make_calc() == True:
            print(symbol)

然后在 execute.map

中添加一个额外的参数
for _ in executor.map(filter_2ndconfirm_workers, adjusted_symbol_list, date_variable):

第二个选项通常更好,因为每个进程都使用自己的 date_variable 副本,但您的选择可能取决于不同的因素,例如变量的大小,以及您是否在函数。

【讨论】:

  • 所以我刚刚发现 date_variable 也应该是一个类似于adjusted_symbol_list 的列表。谢谢迈克
猜你喜欢
  • 2012-07-24
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-08
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多