Skip to main content
 首页 » 编程设计

python之只需键入文件夹名称即可运行 python 模块

2024年10月01日14三少

我在名为 test_module 的文件夹中有 __init__.py。在 __init__.py 我有下面的代码。但是,当我尝试使用以下命令从 test_module 的父文件夹执行时 python test_module 我收到以下错误 can't find '__main__' module in 'test_module。这不可能吗?还是我必须运行 python test_module/__init__.py?

def main(): 
    print('test') 
 
 
if __name__ == '__main__': 
    main() 

请您参考如下方法:

导入包时执行__init__.py模块。 __init__.py 文件的目的根据 documentation如下:

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

为了直接执行 Python 包,它需要有一个入口点,由名为 __main__.py 的包内的模块指定。因此错误 can't find '__main__' module in 'test_module': You Have attempted to directly execute the package, but Python cannot locate an entry point to begin executing top-level code。


考虑以下包结构:

test_module/ 
    __init__.py 
    __main__.py 

其中 __init__.py 包含以下内容:

print("Running: __init__.py") 

其中 __main__.py 包含以下内容:

print("Running: __main__.py") 

当我们使用命令python test_module 执行test_module 包时,我们得到以下输出:

> python test_module 
Running: __main__.py 

但是,如果我们进入 Python shell 并import test_module,输出如下:

>>> import test_module 
Running: __init__.py 

因此,为了在尝试直接执行 test_module 时获得您想要的行为,只需在 test_module 中创建一个新的 __main__.py 文件并将代码从 __init__.py 转移到新的 __main__.py。