Peter Pik
Peter Pik

Reputation: 11193

run python module by just typing folder name

I have __init__.py in a folder called test_module. in the __init__.py i have below code. however when i try to execute from parent folder of test_module with following command python test_module i get following error can't find '__main__' module in 'test_module. is this not possible? or will i have to run python test_module/__init__.py?

def main():
    print('test')


if __name__ == '__main__':
    main()

Upvotes: 2

Views: 2358

Answers (1)

Erick Shepherd
Erick Shepherd

Reputation: 1443

The __init__.py module is executed when the package is imported. The purpose of __init__.py files per the documentation is as follows:

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.

In order for a Python package to be directly executed, it needs to have an entry point, designated by a module within the package named __main__.py. Thus the error 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.


Consider the following package structure:

test_module/
    __init__.py
    __main__.py

Where __init__.py contains the following:

print("Running: __init__.py")

Where __main__.py contains the following:

print("Running: __main__.py")

When we execute the test_module package with the command python test_module, we get the following output:

> python test_module
Running: __main__.py

However, if we enter the Python shell and import test_module, the output is as follows:

>>> import test_module
Running: __init__.py

Thus in order to get the behavior you want when attempting to directly execute test_module, simply create a new __main__.py file within test_module and transfer the code from __init__.py to the new __main__.py.

Upvotes: 3

Related Questions