2017-09-24 186 views
0

我有一個稱爲命令的模塊文件夾。Python模塊導入*

這些模塊每個都有一個唯一的命名函數。

從主目錄,一個與命令的文件夾,我有一個main.py

我可以導入所有模塊與from commands import *

有沒有辦法導入內部的所有函數的所有模塊無需單獨導入它們。即使使用for循環也沒問題。

+0

不'從命令import *'失敗?這聽起來像應該起作用。另外:在命令文件夾中是否有'__init __。py'文件? – JacobIRR

+0

@JacobIRR不會失敗。你讀過這個問題了嗎? – Qwerty

+0

啊,現在我明白了。所以模塊的內部函數只能通過調用'somemodule.somefunction()'而不是隻能調用'somefunction()'來使用? – JacobIRR

回答

1

假設您有一個包含一些Python文件(.py)和一個main.py(位於同一目錄中)的目錄,您希望其他文件的所有功能都可用。這裏是一個天真的做法(一個壞主意,真的),當然,注意名稱衝突:

main.py

from os import listdir 
from importlib import import_module 

for file in listdir('.'): 
    if file.endswith('.py') and file not in __file__: 
     module_name = file[:file.index('.py')] 
     # if you want all functions to just this file (main.py) use locals(); if you want the caller of main.py to have access, use globals() 
     globals().update(import_module(module_name).__dict__) 

# Functions defined in all other .py files are available here