[英]Python multiprocessing calling function from module
我有一個帶my_func()
函數的my_module
模塊。 當我在父進程中使用此函數時,一切都運行良好(我從此函數得到正確的結果)。 但是當我從子進程調用此函數時,我收到此錯誤:
AttributeError: module 'my_module' has no attribute 'my_func'
有誰知道我做錯了什么? 這是我的模板代碼:
import pandas as pd, gc, sys, multiprocessing as mp, traceback as tb
sys.path.append('c:/my_libs/')
import my_module
def mp_func(df, i):
df['res'] = df.apply(lambda x: my_module.my_func(x, i))
return df
def other_function(df):
# do something
my_list = [1,2,3] # it can change dynamically based on previous code
df_res = pd.DataFrame()
mp_pool = mp.Pool(processes=min(len(my_list), mp.cpu_count()))
try:
for i_df in [y.get() for y in [mp_pool.apply_async(mp_func\
, [df[['my_attr']], i]) for i in my_list]]:
df_res = df_res.append(i_df)
except Exception as e:
print('Something went wrong during multiprocessing:\n', e)
print('\nFull traceback:\n', tb.format_exc())
finally:
mp_pool.close()
gc.collect()
df_res.to_csv(<...>)
if __name__ == '__main__':
df = pd.read_csv(<...>)
other_function(df)
而my_module
模塊看起來像這樣:
def my_func(x, i):
return x * i
同樣,如果我運行相同代碼的NOT多處理版本,那么一切都運行良好。 (我使用python 3)
謝謝!
最后我發現了問題。 我使用Spyder,並在其中將默認工作目錄設置為另一個文件夾,其中我有一個以前版本的模塊。 本主題幫助我打印出子進程中導入模塊的路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.