可以从IDLE运行多处理Process类 [英] Can multiprocessing Process class be run from IDLE
问题描述
多处理Process类的基本示例在从文件而不是从IDLE执行时运行.为什么会这样并且可以做到吗?
A basic example of multiprocessing Process class runs when executed from file, but not from IDLE. Why is that and can it be done?
from multiprocessing import Process
def f(name):
print('hello', name)
p = Process(target=f, args=('bob',))
p.start()
p.join()
推荐答案
是.该功能f
的以下工作在单独的(第三)进程中运行.
Yes. The following works in that function f
is run in a separate (third) process.
from multiprocessing import Process
def f(name):
print('hello', name)
if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
p.join()
但是,要查看print
输出,至少在Windows上,必须从这样的控制台启动IDLE.
However, to see the print
output, at least on Windows, one must start IDLE from a console like so.
C:\Users\Terry>python -m idlelib
hello bob
(在2.x上使用idlelib.idle
.)原因是IDLE在单独的进程中运行用户代码.当前,IDLE进程和用户代码进程之间的连接是通过套接字进行的.通过多处理完成的派生不会复制或继承套接字连接.通过图标或资源管理器启动IDLE(在Windows中)时,打印输出无处可去.从具有python
(而不是pythonw
)的控制台启动时,输出将如上所述进入控制台.
(Use idlelib.idle
on 2.x.) The reason is that IDLE runs user code in a separate process. Currently the connection between the IDLE process and the user code process is via a socket. The fork done by multiprocessing does not duplicate or inherit the socket connection. When IDLE is started via an icon or Explorer (in Windows), there is nowhere for the print output to go. When started from a console with python
(rather than pythonw
), output goes to the console, as above.
这篇关于可以从IDLE运行多处理Process类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!