Skip to content

Instantly share code, notes, and snippets.

@razorback16
Created August 31, 2023 21:29
Show Gist options
  • Save razorback16/fffe44a19a486e2418e6ff8fef3ce08d to your computer and use it in GitHub Desktop.
Save razorback16/fffe44a19a486e2418e6ff8fef3ce08d to your computer and use it in GitHub Desktop.
Make a python script installable

To make your Python script installable with pip and have it place a binary/command in /usr/local/bin (or the appropriate bin directory for the environment) that can be run from the command line, follow these steps:

  1. Prepare your package: Create a directory structure that looks something like this:

    my_script/
    ├── my_script/
    │   ├── __init__.py
    │   └── script.py  # Your actual script file
    └── setup.py
    
  2. Setup script (setup.py): Create a setup.py at the root of your package with the following contents:

    from setuptools import setup, find_packages
    
    setup(
        name="my_script",
        version="0.1",
        packages=find_packages(),
        install_requires=[
            # any dependencies your script might have
        ],
        entry_points={
            'console_scripts': [
                'my-script=my_script.script:main',  
            ],
        },
    )

    In the entry_points setting, my-script is the name of the command you'll use to run your script from the command line. my_script.script:main points to the main function in your script.py file. Make sure that your script.py has a function named main which is the entry point of your script.

  3. Main function: In script.py, make sure you have:

    def main():
        # Your script's code here
    
    if __name__ == "__main__":
        main()
  4. Install locally: To install your script locally and have my-script available as a command-line utility, navigate to the directory containing setup.py and run:

    pip install --editable .

    This will install your script in "editable" mode, which means that changes to the source files will immediately affect the installed package.

  5. Upload to PyPI (optional): If you want others to be able to install your script using pip, you can package it and upload it to the Python Package Index (PyPI). There are multiple steps involved, including creating a PyPI account, building your package, and uploading it using a tool like twine. This is a topic in and of itself, but plenty of tutorials are available online if you choose to take this route.

  6. Install from PyPI (after uploading): Once your package is on PyPI, you or anyone else can install it with:

    pip install my_script

    This will install the my-script command globally (or in the active virtual environment) and make it accessible from the command line.

Remember to replace my_script and script.py with the actual name of your package and script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment