开发者

Does python's setuptools support the `__name__ == "__main__"` style of execution?

开发者 https://www.devze.com 2023-02-23 19:01 出处:网络
I\'m just getting into packaging with setuptools, and it seems that the recommended way to install a python script along with one\'s module is to specify a script name that calls the name of a functio

I'm just getting into packaging with setuptools, and it seems that the recommended way to install a python script along with one's module is to specify a script name that calls the name of a function, like this:

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

This clearly precludes the standard way of making a python module executable, which is (last time I checked, which was a while ago) to use if __name__ == "__main__": do_stuff(). Does setuptools 开发者_如何学编程support this style, or should I switch to defining a main function and specifying it in entry_points?


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

Setuptools creates scripts named script_name that imports and runs the function project.main:do_stuff, not run the script directly. You should re-read this part (alternate link, if you use Distribute) of the setuptools docs again to understand why it's this way. The script it creates contains if __name__ == "__main__" still. So yes, this is still the defacto way of making 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's best to define an entry point and a script similar to easy_install. That imports and uses the entry point, like you show in your example if __name__ == "__main__": do_stuff(). It's great for debugging and early testing, also if you use distutils, there is no need to add/change anything. You can also have another app to call do_stuff() to access your app with out the overhead of running it in the shell, which is what setuptools is doing, distutils copy's the script.

0

精彩评论

暂无评论...
验证码 换一张
取 消