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:
-
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 -
Setup script (
setup.py): Create asetup.pyat 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_pointssetting,my-scriptis the name of the command you'll use to run your script from the command line.my_script.script:mainpoints to themainfunction in yourscript.pyfile. Make sure that yourscript.pyhas a function namedmainwhich is the entry point of your script. -
Main function: In
script.py, make sure you have:def main(): # Your script's code here if __name__ == "__main__": main()
-
Install locally: To install your script locally and have
my-scriptavailable as a command-line utility, navigate to the directory containingsetup.pyand 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.
-
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 liketwine. This is a topic in and of itself, but plenty of tutorials are available online if you choose to take this route. -
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-scriptcommand 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.