当我运行下面的代码时,全局变量 'ticker' 没有在 compile() 函数中定义。
目标:如何将多个变量传递给多处理 pool.map() 函数以使此代码正常工作?
帖子底部的代码适用于单个自动收报机,但我无法将其转换为 for 循环。
import multiprocessing
from multiprocessing import Pool
global ticker
global lst
lst = ['BABA','MSFT','NVDA']
def compile(file_list):
print(file_list)
print(f'C: {ticker}')
def main():
print(f'B: {ticker}')
file_list = [1,2,3]
with Pool(multiprocessing.cpu_count()-2) as pool:
results_df = pool.map(compile, file_list)
print(f'D: {ticker}')
if __name__ == '__main__':
for ticker in lst:
print(f'A: {ticker}')
main()
输出:
A: BABA
B: BABA
1
2
3
multiprocessing.pool.RemoteTraceback:
Traceback (most recent call last):
File "/Users/xxx/opt/anaconda3/lib/python3.9/multiprocessing/pool.py", line 125, in worker
result = (True, func(*args, **kwds))
File "/Users/xxx/opt/anaconda3/lib/python3.9/multiprocessing/pool.py", line 48, in mapstar
return list(map(*args))
File "/Users/xxx/Desktop/OptionsData/example 2.py", line 12, in compile
print(f'C: {ticker}')
NameError: name 'ticker' is not defined
我试过将 for 循环放在 if name=='main' 语句之前,虽然输出不同,但仍然不正确(我是否将 for 循环放在正确的位置?)。
我已经尝试将多个参数传递给 pool.map 多处理函数
results_df = pool.map(compile, file_list, ticker)
但它说“在‘str’和‘int’的实例之间不支持。
以下代码适用于单个自动收报机,我想把它变成一个 for 循环以在多个自动收报机上运行,但一直无法让它工作:
import multiprocessing
from multiprocessing import Pool
def compile(file_list):
print(file_list)
print(f'C: {ticker}')
def main():
print(f'B: {ticker}')
file_list = [1,2,3]
with Pool(multiprocessing.cpu_count()-2) as pool:
results_df = pool.map(compile, file_list)
print(f'D: {ticker}')
global ticker
ticker ='BABA'
if __name__ == '__main__':
print(f'A: {ticker}')
main()
输出:
A: BABA
B: BABA
1
C: BABA
2
C: BABA
3
C: BABA
D: BABA
[Finished in 347ms]