首页 > 解决方案 > ProcessPoolExecuter 和全局变量

问题描述

我有一个关于全局变量和使用不同进程的问题。

对于我的主要 python 脚本,我有一个 main 函数,它调用 Initialize 来初始化 Metrics.py 中的全局变量。我还创建了一个 getter 函数来检索这个变量。

主要.py:

from Metrics import *
import pprint

def doMultiProcess(Files):
   result = {}

   with concurrent.futures.ProcessPoolExecutor() as executor:
      futures = [executor.submit(ProcessFile, file) for file in Files]

   for f in concurrent.futures.as_completed(futures):
      # future.result needs to be evaluated to catch any exception
      try:
         filename, distribution = f.result()

         result[filename] = {}
         result[filename] = distribution
      except Exception as e:
         pprint.pprint(e)  
   
   return result 

Files = ["A.txt", "B.txt", "C.txt"]

def main:
   Initialize()

   results = doMultiProcess(Files)
   
if __name__ == '__name__':
    main()

指标.py

Keywords = ['pragma', 'contract']

def Initialize():
   global Keywords
   Keywords= ['pragma', 'contract', 'function', 'is']

def GetList():
   global Keywords             # I believe this is not necessary.
   return Keywords

def ProcessFile(filename):
   # Read data and extract all the words from the file, then determine the frequency 
   # distribution of the words, using nltk.freqDist, which is stored in: freqDistTokens
   distribution = {keyword:freqDistTokens[keyword] for keyword in Keywords}

   return (filename, distribution)

我希望我已经足够简化了示例,并且没有遗漏重要信息。现在,我不明白为什么这些流程继续使用包含“pragma”和“contract”的关键字的初始值。我在实际运行进程之前调用了初始化,因此应该将全局变量设置为与初始值不同的值,对吗?我错过了这里发生的事情。

我已经通过使用 GetList() 函数实际向进程提供关键字列表来解决这个问题,但我想了解为什么会发生这种情况。

标签: pythonconcurrent.futures

解决方案


推荐阅读