[問題] 如何import所有來自指定目錄的module

看板Python作者 (薇薇安安)時間2年前 (2022/03/29 08:00), 2年前編輯推噓4(408)
留言12則, 6人參與, 1年前最新討論串1/3 (看更多)
各位好,以下是本人要處理的檔案 main.py containers /module1.py /module2.py /module3.py module1, 2, 3中的程式碼類似,皆如下: class Test1(self): def __init__(self, num): self.num = num def test1(self): print("test1") 我現在想在main.py中import所有在module1,2,3中的class,但是如果寫成 from module1 import * from module2 import * from module3 import * 好像不太好,之後在containers裡還會增加很多module 不知道各位版友有沒有什麼好方法? 我查過一些資料,像這篇裡有些人去修改__all__,或是使用pkgutil https://reurl.cc/AKNxqj 但我都沒有成功 我嘗試過用importlib for name in os.listdir("containers"): if name.endswith(".py"): module = name[:-3] importlib.import_module(module) 但還是沒有辦法將所有module匯入 import_module 好像只能這樣用: x = importlib.import_module(module1) x.test1.test1() 還有看過一個方法是: for name in os.listdir("containers"): if name.endswith(".py"): module = name[:-3] test_spec = importlib.util.spec_from_file_location(module, "containers/" + module + ".py") test_module = importlib.util.module_from_spec(test_spec) test_spec.loader.exec_module(test_module) 我以為執行完上面這幾行後,可以直接用Test1.test1(),程式裡還是找不到Test1 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 108.254.89.199 (美國) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1648512048.A.09F.html

03/29 08:08, 2年前 , 1F

03/29 08:11, 2年前 , 2F
在子資料夾內寫個__init__.py,裡面把所有.py import
03/29 08:11, 2F

03/29 08:11, 2年前 , 3F
,外面main.py直接import即可,這是做package的方法
03/29 08:11, 3F

03/29 12:55, 2年前 , 4F
應該是想問有沒有dynamic方式去import而不用一個個寫
03/29 12:55, 4F

03/29 13:19, 2年前 , 5F
關鍵字是 importlib
03/29 13:19, 5F

03/29 16:17, 2年前 , 6F
eval('from '+pyfilename.replace('.py','')+'import *')
03/29 16:17, 6F

03/29 16:18, 2年前 , 7F
不過要先拿到檔案列表放迴圈
03/29 16:18, 7F

03/29 16:51, 2年前 , 8F
eval不能拿來import
03/29 16:51, 8F

03/29 17:06, 2年前 , 9F
那是我錯了
03/29 17:06, 9F
※ 編輯: VivianAnn (108.254.89.199 美國), 03/29/2022 17:42:09

03/29 18:06, 2年前 , 10F
不要拿eval做危險的事…
03/29 18:06, 10F

03/29 22:15, 2年前 , 11F
是可以改用exec做import,但一樣不建議
03/29 22:15, 11F

03/31 22:13, 1年前 , 12F
易讀性跟後續程式碼分析,一般還是會寫__all__就是
03/31 22:13, 12F
文章代碼(AID): #1YGamm2V (Python)
文章代碼(AID): #1YGamm2V (Python)