2017-06-06 65 views
2

我在test_module的文件夹中有__init__.py。在__init__.py我有下面的代码。但是,当我尝试从test_module父文件夹执行以下命令python test_module我得到以下错误can't find '__main__' module in 'test_module。这是不可能的?或者我将不得不运行python test_module/__init__.py只需键入文件夹名称即可运行python模块

def main(): 
    print('test') 


if __name__ == '__main__': 
    main() 
+2

尝试使用['python -m test_module'](https://docs.python.org/2/using/cmdline.html#cmdoption-m) – dhke

+0

您能解释一下为什么要这样做吗?它似乎不是非常pythonic – Y0da

回答

2

__init__.py模块在导入包时执行。每次完成的documentation__init__.py文件的目的如下:

__init__.py文件,才能使Python视该目录为一个包;这是为了防止具有通用名称的目录(例如字符串)无意中隐藏稍后在模块搜索路径中发生的有效模块。在最简单的情况下,__init__.py可以只是一个空文件,但它也可以执行包的初始化代码或设置__all__变量,稍后介绍。

为了使Python包被直接执行,它需要有一个入口点,由名为__main__.py封装内的模块指定。因此,错误can't find '__main__' module in 'test_module':您试图直接执行该程序包,但是Python无法找到开始执行顶级代码的入口点。


考虑以下封装结构:

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外壳和import test_module,输出如下:

>>> import test_module 
Running: __init__.py 

因此,为了在尝试直接执行test_module时获得所需的行为,只需在test_module内创建一个新的__main__.py文件并将代码f rom __init__.py到新的__main__.py

相关问题