Search code examples
pythondistutilssetup.pyshebang

How to deal with a script which has shebang line in setup script?


I have the following structure of my distribution source:

|project
    |setup.py
    |project.py
    |package
        |__init__.py
        |code.py

project.py is the main script and it has shebang line.

Should I define somehow the above mentioned fact in setup.py?


Solution

  • You'll want to look at the setuptools console_scripts entry point.

    Say your project.py currently contains something like this:

    if __name__ == '__main__':
        run_proj()
    

    You need to move first move project.py inside the package directory to be able to reference it from setup.py. Then, register the run_proj function with the console_scripts entry point like this:

    setup.py

    setup(
        # other arguments here...
        entry_points={
            'console_scripts': [
                'run-proj = package.project:run_proj',
            ],
        }
    )
    

    After that, you'll need to re-run setup.py, for example by doing python setup.py develop, or whichever method you're using during development.

    Then you'll get a bin/run-proj script that calls run_proj(), and can be called from the command line. (If you install the package in a virtual env, that will be in venv/bin/run-proj, or if you install it system-wide, somewhere like usr/local/bin/run-proj, depending on your OS / distro).

    That script should actually be on your path, so you should be able to just run run-proj from the shell.

    At this point, the shebang line isn't really necessary any more, and you can remove it (the bin/run-proj will have an automatically generated shebang pointing to the proper Python interpreter).