python - Python 多处理不是按项目执行,而是按字符执行
问题描述
我有多个环境(DEV、INT、PRD)。我想使用 python 多处理异步构建每个环境。
在下面的示例中,build_environments 是这样的列表:['DEV', 'UAT', 'PRD']。
def thread_set(self,environment):
max_workers = 3
concurrent = futures.ThreadPoolExecutor(max_workers)
with concurrent as ex:
ex.map(self.build, environment)
return environment
def multibuild(self):
build_environments = self.myparser.getEnvironments()
with multiprocessing.Pool(processes=4, maxtasksperchild=1) as pool:
results = pool.imap(self.thread_set, build_environments)
pool.close()
pool.join()
def build(self,build_environment):
print(build_environment)
当我执行 multibuild() 时,build() 函数中的打印语句正在以这种方式打印和执行,如下所示。
U
A
T
D
E
V
P
R
D
但我希望 build() 打印功能是:
DEV
UAT
PRD
可能是什么问题 ?
解决方案
使用print
不是线程安全的。请改用日志记录。
import logging
# environment is a string which is iterable, only one
# character is getting passed to build
def thread_set(self,environment):
max_workers = 3
concurrent = futures.ThreadPoolExecutor(max_workers)
with concurrent as ex:
ex.map(self.build, (environment,)) # place environment in a container, a list should work, too.
return environment
# replace the print statement with logging
def build(self,build_environment):
# print(build_environment) (Not thread-safe.)
logging.info(build_environment)
参考:Python 线程简介
推荐阅读
- c# - c# - 在 void 之间传递字符串并在计时器中更新
- flutter - 颤振运行 pub 运行 build_runner 构建失败
- python - 如何越来越多地迭代多个迭代器?
- android-coordinatorlayout - MotionLayout 作为 CoordinatorLayout 的父级打破了滚动
- debugging - 如何使用 OpenEdge 调试器 (OpenEdge Debugger 11.6)
- reactjs - 在 React / Typescript / Redux 运行时更改 Monaco 编辑器选项
- google-api - 用于 .Net 核心的服务器端应用程序的 Google 登录
- c - 假设指向同一个变量的两个指针是非法的/UB,为什么 C 编译器不能优化更改 const 指针的值?
- request - Chrome 开发工具。没有内容长度标头时如何检查请求的传出大小?
- c# - PowerBI Embed 令牌请求返回错误“提供的角色无效”