Python中无法从子目录导入*。

3

我想从子目录中导入一组模块到父目录下的一个主模块中:

项目/

main.py
subdirectory/
    __init__.py
    timer.py
    example.py

我可以这样请求任何一个.py文件:

from subdirectory import timer.py

但是,如果我运行以下命令:

from subdirectory import *

当我尝试使用子目录中的一个模块时,出现以下错误:
File "My:\Path\Here\...", line 33, in main
t = timer.timer()
NameError: name 'timer' is not defined

我希望能够一次性导入所有文件,因为我正在导入几个模块。我已经在子目录中添加了一个空的init.py文件。 我是否漏掉了什么?

3个回答

3
你必须在你的__init__.py文件中使用__all__来声明你的模块名:
__all__ = ["timer", "example"]

这种行为已有文档记录:

唯一的解决方案是由包的作者提供一个明确的包索引。 import 语句使用以下约定:如果包的 __init__.py 定义了一个名为 __all__ 的列表,则该列表被视为在遇到 from package import * 时应导入的模块名称列表。


非常感谢!现在import *语句正常工作,我可以使用导入的模块了。 - Lee

2
如果你只想让导入起作用,那么请添加 subdirectory/__init__.py 文件,并包含以下内容:
from * import example
from * import timer

然而,如果您想对任意数量的(旧的和新的)模块执行此操作,我认为这个答案可能是您要寻找的:

您可以从以下结构开始:

main.py
subdirectory/
subdirectory/__init__.py
subdirectory/example.py
subdirectory/timer.py

然后从main.py导入subdirectory中的所有内容:

from subdirectory import *
t = timer.timer()

接下来将以下内容添加到subdirectory/__init__.py模块中:

from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not 
f.endswith('__init__.py')]

为了完整起见,subdirectory/timer.py模块如下:
def timer():
    return 42

from * import example 是语法错误。我认为你想要使用 from . import example - tdelaney
谢谢您的回答。那个来源确实提供了很好的解决方案。 - Lee

0

导入通常是这样的。

# if you have timer.py, import it as 
import timer

尝试在子目录中添加__init__.py。 现在它看起来像这样:

Project/


    main.py
    subdirectory/
                 __init__.py
                 timer.py
                 example.py

如果那不起作用: 在main.py中添加
import sys
sys.path.append("path/to/subdirectory") # replace with the path
import timer

我已经完成了。 - Lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接