問題描述
我在 Windows 機器上使用 IPython 和 Spyder IDE.當 IDE 啟動時,會加載一組 py 文件來定義一些使我的工作更輕松的函數.一切正常.
I'm working with IPython and Spyder IDE on a Windows machine. When the IDE is starting, a set of py-files is loaded to define some functions that make my work a bit easier. Everything works as expected.
現在我想升級其中一個功能以使用多處理,但在 Windows 上,這需要 if __name__ == "__main__":
語句.因此,我似乎無法直接調用該函數并從 IPython 控制臺傳遞參數.
Now I would like to upgrade one of these function to use multiprocessing, but on Windows this requires the if __name__ == "__main__":
statement. So it seems that I cannot call the function directly and pass the arguments from the IPython console.
例如,其中一個 py 文件(我們稱之為 test.py)可能類似于以下代碼.
For example one of the py-files (let's call it test.py) could look like the following code.
import multiprocessing as mp
import random
import string
# define a example function
def rand_string(length, output):
""" Generates a random string of numbers, lower- and uppercase chars. """
rand_str = ''.join(random.choice(
string.ascii_lowercase
+ string.ascii_uppercase
+ string.digits)
for i in range(length))
output.put(rand_str)
def myFunction():
# Define an output queue
output = mp.Queue()
# Setup a list of processes that we want to run
processes = [mp.Process(target=rand_string, args=(5, output)) for x in range(4)]
# Run processes
for p in processes:
p.start()
# Exit the completed processes
for p in processes:
p.join()
# Get process results from the output queue
results = [output.get() for p in processes]
print(results)
在我的 IPython 控制臺中,我想使用該行
In my IPython console I would like to use the line
myFunction()
觸發所有計算.但在 Windows 上,最終會出現 BrokenPipe 錯誤.
to trigger all the calculations. But on Windows a end up getting a BrokenPipe error.
當我放
if __name__ == "__main__":
myFunction()
在 py 文件的末尾并運行完整的文件
at the end of the py-file and run the complete file by
runfile(test.py)
它有效.當然.但這使得向函數傳遞參數變得非常困難,因為我總是必須編輯 test.py 文件本身.
it works. Of course. But that makes it very hard to pass arguments to the function as I always have to edit the test.py-file itself.
推薦答案
所以,我解決了那個具體問題.
So, I solved that specific problem.
把
rand_string
的定義放在一個單獨的文件中,叫做test2
.
Put the defintion of
rand_string
in a separate file, calledtest2
.
將 test2
作為模塊導入我的 test.py
腳本
Import test2
as module into my test.py
script
將 test2 導入為 test2
修改以下行以訪問 test2
模塊
modify the following line to access the test2
module
processes = [mp.Process(target=test2.rand_string, args=(5, output)) for x in range(4)]
運行 test.py
調用myFunction()
要快樂:)
解決方案基于此多處理教程建議從另一個腳本導入目標函數.此解決方案繞過 if __name__
-wrapper 的安全自導入以訪問目標函數.
The solution is based on this multiprocessing tutorial that suggests to import the target function from another script. This solution bypasses the safe self import by the if __name__
-wrapper to get access to the target function.
這篇關于Windows 機器上 IPython 控制臺中的多處理 - 如果 __name_ 要求的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!