Setuptools, __init__ and __main__
Paul Moore
p.f.moore at gmail.com
Fri Feb 6 18:03:56 EST 2015
On Friday, 6 February 2015 22:20:58 UTC, Rob Gaddi wrote:
> I found a recommendation at https://chriswarrick.com/blog/2014/09/15/
> python-apps-the-right-way-entry_points-and-scripts/ that seems to say
> that I should get around this by simply having an empty __init__. I
> guess I can move the program to foobar.py, have an empty __init__, a stub
> __main__ that just calls foobar.main(), and an entry-point of
> foobar.foobar:main . It just feels like a bit of a heavy solution to
> have two unnecessary files.
There's no real reason you have to take your code out of __init__.py, it's fine there. What it sounds like to have is a chunk of code that is basically the command line interface to your application. Presumably, if you've set things up for an entry point, that code is in a main() function. So the following should work:
-- mypkg
|
-- __init__.py
def main():
# whatever
-- __main__.py
import mypkg
mypkg.main()
Then define your entry point as calling mypkg:main
This will give you an entry point script when you install your project, and the __main__.py file means that "python -m mypkg" will also work.
If you want a working example, pip itself uses this structure (although it's a bit more complicated because pip's a bit bigger :-))
Hope this helps,
Paul
More information about the Python-list
mailing list