[Tutor] if __name__=='main' vs entry points: What to teach new comers?
Cameron Simpson
cs at cskk.id.au
Thu Aug 3 21:57:07 EDT 2017
On 03Aug2017 00:57, Steven D'Aprano <steve at pearwood.info> wrote:
>Can you explain the use-case for when somebody might want to use
>console_scripts entry points?
>
>I have a module with a main() function and an "if __name__ == ..."
>guard. Under what circumstances is that not sufficient, and I would want
>console_scripts?
I have a bunch of "one liner" scripts in my personal "bin" directory like this
one:
#!/bin/sh
#
# Run the named port forwards indefinitely.
# - Cameron Simpson <cs at zip.com.au> 08jul2008
#
# Convert to Python module cs.app.portfwd. - cameron, may2017
#
exec python3 -m cs.app.portfwd ${1+"$@"}
It relies on the __main__ thing in the cs.app.portfwd module, and many of my
modules have a main, as I gather do yours.
For a lot of modules that main just runs the selftests, but for some the main
is a perfectly reasonable command, such as "portfwd" above. So an install
implies having an invocation script. By hand, I can do the above script.
But if I'm distributing the module via PyPI, how do I install the invocable
script in the $PATH eg the virtualenv's bin? The installer knows where the
"bin" is, but on windows the script install is not the same as on UNIX.
So the console_scripts dict provides a mapping from script names to
module.function callables, and setup installs the right thing. It also
separates the script name from the module/function names.
Also, modules are groups by function topic. A module may have more than one
function within it which are suitable command line implementations. The
console_scripts mapping lets one bind multiple script to suitable entry points.
Cheers,
Cameron Simpson <cs at cskk.id.au> (formerly cs at zip.com.au)
More information about the Tutor
mailing list