python - 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() 函数实际向进程提供关键字列表来解决这个问题,但我想了解为什么会发生这种情况。
解决方案
推荐阅读
- javascript - 如何在 Phaser 3 中移除玩家和地面之间的空白空间
- python - 我应该将我的项目版本提交到 Git 吗?
- bash - && 和 || 的区别 Bash 中的运算符
- php - fgetc() 函数读取整个文件
- node.js - 当由 `yarn` 安装时,来自 Git 存储库的 `npm` 依赖项无法正确构建
- angular - Angular 单元测试 HTTP 错误拦截器 catchError/ErrorEvent/Error
- reactjs - 是一个使用仅返回api响应的useeffect的函数可以在另一个组件的方法中调用吗?
- vue.js - 我想通过 v-html 使用 vue 过滤器后使用 queryselectorall
- javascript - 将 GraphQL 错误存储为字符串
- python - 如何解决 Django 格式错误:AttributeError: 'Habit' object has no attribute 'goal'