問題描述
多處理進程類的基本示例在從文件執行時運行,而不是從 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:UsersTerry>python -m idlelib
hello bob
(在 2.x 上使用 idlelib.idle
.)原因是 IDLE 在單獨的進程中運行用戶代碼.目前,IDLE 進程和用戶代碼進程之間的連接是通過套接字進行的.多處理完成的分叉不會復制或繼承套接字連接.通過圖標或資源管理器(在 Windows 中)啟動 IDLE 時,打印輸出無處可去.當使用 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 運行多處理進程類嗎的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!