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

2024-09-27 07:29:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望将一组模块从子目录导入父目录中的单个主模块:

项目/

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文件。 有什么我遗漏的吗


Tags: 模块文件项目frompyimport命令目录
3条回答

必须在__init__.py中使用__all__声明模块名称:

__init__.py

__all__ = ["timer", "example"]

这种行为是documented

The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered.

如果只想使导入工作,请添加具有以下内容的subdirectory/__init__.py

from * import example
from * import timer

但是,如果您想对任意数量的(旧的和新的)模块执行此操作,我认为this answer可能就是您想要的:

您可以从以下结构开始:

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

进口是这样的

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

尝试将__init__.py添加到子目录。 它现在看起来像:

项目/


    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

相关问题 更多 >

    热门问题