最新消息: USBMI致力于为网友们分享Windows、安卓、IOS等主流手机系统相关的资讯以及评测、同时提供相关教程、应用、软件下载等服务。

Python:multiprocessing示例代码在Windows环境无法运行的解决方案

业界 admin 2浏览 0评论

文章目录

  • 前言
  • 1. 问题描述
  • 2. 解决方案
  • 3. 原因浅析

前言

记录multiprocessing模块在Windows环境下遇到的问题。

1. 问题描述

初次使用Python提供的multiprocessing模块,文档中分明写着同时支持Linux和Windows。

It runs on both Unix and Windows.(摘录自官方文档)

但在IDEA/Windows环境下跑了一下官方提供的例子,结果卡住不输出结果,代码如下,出自:https://docs.python/3/library/multiprocessing.html。

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))

# 应该输出:[1, 4, 9]

2. 解决方案

在网上找了一些文章,总结下来,有两点需要注意:
一是要把代码放在if __name__ == '__main__'里面,上面的例子代码中已经满足要求了。

二是要放在终端下运行。

这个答案是在stackoverflow上找到的,但仍然有需要注意的地方。
在IDEA里面打开终端(Terminal),运行python test.py,也是不行的。

必须单独打开一个Windows终端工具才行。

3. 原因浅析

为什么在Windows的图形界面软件中运行上面的代码都不行呢,在stackoverflow的这个回答
中,Terry Jan Reedy给出了解释。

The problem is not IDLE. The problem is trying to print to sys.stdout in a process that has no sys.stdout. That is why Spyder has the same problem. Any GUI program on Windows is likely to have the same problem.

翻译:
问题不在IDLE(译注:包括IDEA等开发环境)。问题是,在一个没有sys.stdout的进程中试图打印到sys.stdout。这就是为什么Spyder也有同样的问题。任何Windows下的GUI程序似乎都有同样的问题。

文章目录

  • 前言
  • 1. 问题描述
  • 2. 解决方案
  • 3. 原因浅析

前言

记录multiprocessing模块在Windows环境下遇到的问题。

1. 问题描述

初次使用Python提供的multiprocessing模块,文档中分明写着同时支持Linux和Windows。

It runs on both Unix and Windows.(摘录自官方文档)

但在IDEA/Windows环境下跑了一下官方提供的例子,结果卡住不输出结果,代码如下,出自:https://docs.python/3/library/multiprocessing.html。

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))

# 应该输出:[1, 4, 9]

2. 解决方案

在网上找了一些文章,总结下来,有两点需要注意:
一是要把代码放在if __name__ == '__main__'里面,上面的例子代码中已经满足要求了。

二是要放在终端下运行。

这个答案是在stackoverflow上找到的,但仍然有需要注意的地方。
在IDEA里面打开终端(Terminal),运行python test.py,也是不行的。

必须单独打开一个Windows终端工具才行。

3. 原因浅析

为什么在Windows的图形界面软件中运行上面的代码都不行呢,在stackoverflow的这个回答
中,Terry Jan Reedy给出了解释。

The problem is not IDLE. The problem is trying to print to sys.stdout in a process that has no sys.stdout. That is why Spyder has the same problem. Any GUI program on Windows is likely to have the same problem.

翻译:
问题不在IDLE(译注:包括IDEA等开发环境)。问题是,在一个没有sys.stdout的进程中试图打印到sys.stdout。这就是为什么Spyder也有同样的问题。任何Windows下的GUI程序似乎都有同样的问题。

发布评论

评论列表 (0)

  1. 暂无评论