Today I want to show you how you can turn a python script from this:
$ python3 coolscript.py
How It’s Done
How you are able to change a python script into a full fledged CLI command is by leveraging setup.py. I will demonstrate this by creating a program that will perform a caesar cipher on any text you provide it.
First we will need to create our projects directory:
$ mkdir caesar
$ cd caesar
$ mkdir caesar
$ touch setup.py
$ touch caesar/__init__.py
$ touch caesar/caesar.py
And what we should be left with is a directory structure that looks like this:
| |-- __init__.py
| `-- caesar.py
Once you have the directory setup we will create the script in caesar.py. The objective of this tutorial is not to teach you how to create the script however I will add it below if you are interested.
Also we will need to make one change in our __init__.py file to allow our script to be accessed inside the directory.
Now that we have completed our script it is time to fill out our setup.py
Lets break down this file line by line. First we are importing setuptools which is the standard library used by Python for building scripts. Next we call the setup function of setuptools and pass in the required parameters. The parameter we want to focus on the most is entry_points
- name: The name of the script
- version: The version number of your script
- author: Your name
- author_email: Your email
- description: A short description of what your script does
- packages: The packages required for your script
- entry_points: Basically how to interact with your script. In the example we are specifying console_scripts which is the most popular entry point since it allows us to specify a cli command to our script
- classifiers: Specifications for users to understand what language and OS is required to run your script
In our above setup.py file we specified the following for our entry point
'caesar = caesar.caesar:main'
Here we are configuring the command caesar to be related to our main function in our caesar.py script file. Now when we execute our setup.py file it should build and install our script and allow us to access it using the caesar command.
$ sudo python3 setup.py install
Now that our script has been built lets try to use it on the CLI
$ caesar "Test Message"
$ caesar "Whvw Phvvdjh" --decrypt
And it worked! We can now use our script as a CLI command.
Creating a setup.py file is an important step for any python project since it allows you to provide information to users about the file and allows you to create extra functionality to the script such as adding it as a CLI command.
Thanks for reading!
Originally published at ediblesec.com on November 28, 2018.