Search code examples
pythonpipsetuptoolspython-module

module as script without .py in Python?


I want to have a Python file with code called 'foobar' that is meant to be executed as a script when the package is installed as in:

$ foobar -i arg1 arg2

foobar is declared as script in setup.py.

The foobar file also contains functions/classes that are imported by other modules in the package, so there's a separate file quux.py that imports foobar:

(in `quux.py`):
import mypackage
import mypackage.foobar as foobar

How can I keep foobar without the .py extension and declare it as a script in setup.py but still be able to import it from another file as a module? Is this the right answer: Import a python module without .py extension, -- or is there another trick?


Solution

  • In general, the solution here is to leave foobar.py as a module, and have the script be something as simple as:

    import foobar
    foobar.main()
    

    If you're installing your module using setup.py (and you probably should be), you can also do this via console_scripts entry points, like this:

    entry_points={
        'console_scripts': [
            'foobar = foobar:main'
        ],
    },
    

    This will install a foobar command that is roughly equivalent to the stub in the first part of this answer.