Does python setuptools support the `__name__ ==" __main __ "` execution style?

I am just going to pack using setuptools, and it seems that the recommended way to install a python script along with one module is to specify a script name that calls the function name, for example:

setup( # ... entry_points = { "console_scripts": [ "script_name": "project.main:main", ], } ) 

This explicitly excludes the standard way to create a python module executable module, which (the last time I checked it was recently) to use if __name__ == "__main__": do_stuff() . Does setuptools support this style, or do I need to switch to the definition of the main function and specify it in entry_points?

+7
source share
1 answer

This is: "script_name = project.main:do_stuff with setuptools

Setuptools creates scripts called script_name , which imports and runs the project.main:do_stuff , rather than running the script directly. You should re-read this part ( alternative link if you are using Distribute) of the setuptools documents again to understand why. The generated script contains if __name__ == "__main__" . So yes, this is still a de facto way to make it execute.

This is a copy of easy_install installed with setuptools

 #!/usr/bin/python # EASY-INSTALL-ENTRY-SCRIPT: 'distribute==0.6.14','console_scripts','easy_install' __requires__ = 'distribute==0.6.14' import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point('distribute==0.6.14', 'console_scripts', 'easy_install')() ) 

I think it is best to define an entry point and a script similar to easy_install. This imports and uses the entry point, as shown in the example if __name__ == "__main__": do_stuff() . This is great for debugging and early testing, also if you use distutils , there is no need to add / change anything. You may also have another application to call do_stuff () to access your application with the costs of running it in the shell, which is what setuptools works, distutils copies the script.

+9
source

All Articles