簡體   English   中英

Python 上的 `concurrent.futures.ProcessPoolExecutor` 從文件開頭而不是定義的函數運行

[英]`concurrent.futures.ProcessPoolExecutor` on Python is ran from beginning of file instead of the defined function

我對concurrent.futures有疑問。 對於簡短的背景,我試圖用python-opencv2進行大規模的圖像處理。 我偶然發現了性能問題,考慮到處理數百張圖像可能需要數小時,這很痛苦。 我找到了一個解決方案,通過使用concurrent.futures來利用 CPU 多核來加快處理速度(因為我注意到雖然處理時間很長,但它只使用了我的 6 核處理器的 16%,這大約是一個-核)。 所以我創建了代碼,但后來我注意到多處理實際上是從代碼的開頭開始的,而不是圍繞我剛剛創建的函數進行隔離。 這是錯誤的最小工作再現:

import glob
import concurrent.futures
import cv2
import os

def convert_this(filename):
    ### Read in the image data
    img = cv2.imread(filename)
    
    ### Resize the image
    res = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    res.save("output/"+filename)

try:
    #create output dir
    os.mkdir("output")
    with concurrent.futures.ProcessPoolExecutor() as executor:
        files = glob.glob("../project/temp/")
        executor.map(convert_this, files)
except Exception as e:
    print("Encountered Error!")
    print(e)
    filelist = glob.glob("output")
    for f in filelist:
        os.remove(f)
    os.rmdir("output")

它給了我一個錯誤:

Encountered Error!
Encountered Error!
[WinError 183] Cannot create a file when that file already exists: 'output'
Traceback (most recent call last):
  File "M:\pythonproject\testfolder\test.py", line 17, in <module>
    os.mkdir("output")
[WinError 183] Cannot create a file when that file already exists: 'output'
Encountered Error!
[WinError 183] Cannot create a file when that file already exists: 'output'
Traceback (most recent call last):
  File "M:\pythonproject\testfolder\test.py", line 17, in <module>
    os.mkdir("output")
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'output'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\<username>\Anaconda3\envs\py37\lib\multiprocessing\spawn.py", line 105, in spawn_main
Encountered Error!
[WinError 183] Cannot create a file when that file already exists: 'output'
Traceback (most recent call last):
  File "M:\pythonproject\testfolder\test.py", line 17, in <module>
    os.mkdir("output")
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'output'
...
(it was repeating errors of the same "can't create file")

如您所見, os.mkdir已運行,即使它位於我剛剛定義的convert_this函數之外。 我對 Python 並不陌生,但在多處理和線程方面絕對是新手。 這就是concurrent.futures的行為方式嗎? 還是我錯過了一些文檔閱讀?

謝謝。

是的,多處理必須先將文件加載到新進程中,然后才能運行該函數(就像您自己運行文件時一樣),因此它會運行您編寫的所有代碼。 因此,要么(1)將您的多處理代碼移動到一個單獨的文件中,其中沒有任何額外內容並調用它,或者(2)將您的頂級代碼包含在一個函數(例如main() )中,並在您的文件底部寫

If __name__ == ”__main__":
    main()

此代碼只會在您啟動腳本時運行,而不是由多進程生成的版本運行。 有關此構造的詳細信息,請參閱Python 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM