2017-08-09 56 views
1

所以我想創建一個使用python多處理模塊的進程,我希望它是更大腳本的一部分。 (我也想了很多其他的東西,從它,但現在我會滿足於這一點)多處理代碼重複運行

我從multiprocessing docs複製最基本的代碼,並修改了它稍微

然而,一切if __name__ == '__main__':的每次調用p.join()時,語句都會重複重複

這是我代碼

from multiprocessing import Process 

data = 'The Data' 
print(data) 

# worker function definition 
def f(p_num): 
    print('Doing Process: {}'.format(p_num)) 

print('start of name == main ') 

if __name__ == '__main__': 
    print('Creating process') 
    p = Process(target=f, args=(data,)) 
    print('Process made') 
    p.start() 
    print('process started') 
    p.join() 
    print('process joined') 

print('script finished') 

這是我預期

The Data 
start of name == main 
Creating process 
Process made 
process started 
Doing Process: The Data 
process joined 
script finished 

Process finished with exit code 0 

這是現實

The Data 
start of name == main 
Creating process 
Process made 
process started 
The Data       <- wrongly repeated line 
start of name == main   <- wrongly repeated line 
script finished     <- wrongly executed early line 
Doing Process: The Data 
process joined 
script finished 

Process finished with exit code 0 

我不確定這是否是由if聲明或p.join()或其他內容引起的,並且是由爲什麼會發生這種情況。有人可以解釋一下是什麼引起這個和爲什麼

爲了清楚起見,因爲有些人不能複製我的問題,但我有;我正在使用Windows Server 2012 R2 Datacenter,我正在使用python 3.5.3。

+1

使用多處理模塊時,會創建一個全新的python進程,這意味着python腳本基本上是重複的。唯一的區別是新創建的進程會有一個目標方法,並且該目標是執行的目標。任何函數定義之外的所有代碼都以與任何python腳本行爲相同的方式運行。這是我的理解。 – Peter

+2

無法重現您的結果。代碼在我的機器上工作正常,也http://www.tutorialspoint.com/execute_python_online.php?PID=0Bw_CjBb95KQMVFJETFNzZG1rX1U – aristotll

+0

@aristotll我不能exaplain爲什麼它在網上工作,但我已經在兩臺計算機上運行這裏,它每次都失敗 - 但無論如何,謝謝檢查。 –

回答

2

Multiprocessing在Python中的工作方式是,每個子進程都導入父腳本。在Python中,當你導入一個腳本時,所有未在函數中定義的東西都會被執行。據我瞭解,__name__在導入腳本(Check this SO answer here for a better understanding)時發生了改變,這與直接在命令行上運行腳本不同,這會導致__name__ == '__main__'。此導入結果__name__不等於'__main__',這就是爲什麼if __name__ == '__main__':中的代碼未針對您的子流程執行的原因。

任何你不想在子進程調用中執行的東西都應該被移動到你的代碼的if __name__ == '__main__':部分,因爲這隻會在父進程中運行,即你最初運行的腳本。

希望這會有所幫助。如果你環顧四周,Google還有更多的資源可以更好地解釋這一點。我鏈接了多處理模塊的官方Python資源,我建議你仔細看看它。

+0

夢幻般的答案,正是我在找的東西,但是有另一種方法來隱藏子進程中不必要的函數和模塊(嘗試並保存時間和空間)除了將它們包含在'if'語句中還是加載其他函數/類/模塊等花費很少的時間,這是不值得的? –

+0

我不認爲節省的時間會很大 - 這應該不重要。 – Peter

+0

好的,我堅持按照解釋使用它 –