我試圖創建一個__init__.py
文件,該文件將* .py文件中的所有函數從目錄導入命名空間(目錄名稱)。邏輯如下:Python將目錄中的文件的所有功能導入到一個命名空間
for f in os.listdir(wd):
if not f.endswith('.py') or f == '__init__.py':
continue
names = get_public_functions(open(wd + f))
try:
mod = __import__(f[:-3], fromlist=names)
for fn in names:
fun = getattr(mod, fn)
setattr(sys.modules[__name__], fn, fun)
except Exception as e:
for fn in names:
setattr(sys.modules[__name__], fn, lambda: str(e))
所以,你可以看到,如果有語法錯誤,在一個文件中,該功能將仍然需要進口,但他們將返回語法錯誤(作爲一個字符串)。
什麼是令人沮喪的是,當有多個文件的語法錯誤,而我希望是這樣的:
mymodule.fn() => error1,
mymodule.fn2() => error1 (these were from the first file),
mymodule.fn3() => error2 etc.
我只得到了最後一條錯誤消息。我認爲錯誤必須在except
區塊中,但我無法確定。誰能幫忙?
可能重複(http://stackoverflow.com/questions/12423614/local-variables-in -python-nested-functions) – 2013-03-11 15:34:27