Command Line Scripts | Python Packaging
Last Updated :
29 Apr, 2019
How do we execute any script in Python?
$ python do_something.py
$ python do_something_with_args.py gfg vibhu
Probably that's how you do it.
If your answer was that you just click a button on your IDE to execute your Python code, just assume you were asked specifically how you do it on command line.
Let's make it easier for you.
$ do_something
$ do_something_with_args gfg vibhu
That sure looks a lot cleaner. Basically, they are just your python scripts converted to command line tools. In this article, we will discuss how you can do that yourself.
The process can be broken down in these 6 steps:
- Create your Command Line Script.
- Set-up files and folder structure for Packaging.
- Modify your
setup.py
file to incorporate your CLI scripts.
- Test your package before publishing and then Build.
- Upload on pypi and publish your package.
- Install your newly-published package.
The first two steps are comprehensively covered in their respective articles. It's recommended to have a look at them before moving forward. This article will mainly continue from Step 3.
Step #1: Make your Command Line Script
->
gfg.py
Python3 1==
import argparse
def main():
parser = argparse.ArgumentParser(prog ='gfg',
description ='GfG article demo package.')
parser.add_argument('integers', metavar ='N', type = int, nargs ='+',
help ='an integer for the accumulator')
parser.add_argument('-greet', action ='store_const', const = True,
default = False, dest ='greet',
help ="Greet Message from Geeks For Geeks.")
parser.add_argument('--sum', dest ='accumulate', action ='store_const',
const = sum, default = max,
help ='sum the integers (default: find the max)')
args = parser.parse_args()
if args.greet:
print("Welcome to GeeksforGeeks !")
if args.accumulate == max:
print("The Computation Done is Maximum")
else:
print("The Computation Done is Summation")
print("And Here's your result:", end =" ")
print(args.accumulate(args.integers))
Step #2: Set-up files and folder Structure
Step #3: Modify setup.py file
Setuptools allows modules to register entrypoints (
entry_points
) which other packages can hook into to provide certain functionality. It also provides a few itself, including the
console_scripts
entry point.
This allows Python
functions (not scripts!) to be directly registered as command-line accessible tools!
->
setup.py
Python3
from setuptools import setup, find_packages
with open('requirements.txt') as f:
requirements = f.readlines()
long_description = 'Sample Package made for a demo \
of its making for the GeeksforGeeks Article.'
setup(
name ='vibhu4gfg',
version ='1.0.0',
author ='Vibhu Agarwal',
author_email ='[email protected]',
url ='https://github.com/Vibhu-Agarwal/vibhu4gfg',
description ='Demo Package for GfG Article.',
long_description = long_description,
long_description_content_type ="text/markdown",
license ='MIT',
packages = find_packages(),
entry_points ={
'console_scripts': [
'gfg = vibhu4gfg.gfg:main'
]
},
classifiers =(
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
),
keywords ='geeksforgeeks gfg article python package vibhu4agarwal',
install_requires = requirements,
zip_safe = False
)
Step #4: Test & Build
Test: Change the directory to top-level of your package, the same one with
setup.py
file.
Install your intended package by typing in this command.
$ python3 setup.py install
This will install your package if there are no errors in setup.
Now you can test all the functionalities of your package. If anything goes wrong, you can still fix things up.
Build: Make sure you have upgraded pip version along with latest
setuptools
and
wheel
. Now use this command to build distributions of your package.
$ python3 setup.py sdist bdist_wheel
Step #5: Publish the package
twine
is a library that helps you upload your package distributions to pypi. Before executing the following command, make sure you have an account on
PyPI
$ twine upload dist/*
Provide the Credentials and Done! You just got your first Python package published on PyPI.
Step #6: Install the package
Now install your newly published package by using
pip
.
$ pip install vibhu4gfg
Play.
$ gfg
usage: gfg [-h] [-greet] [--sum] N [N ...]
gfg: error: the following arguments are required: N
$ gfg -h
usage: gfg [-h] [-greet] [--sum] N [N ...]
GfG article demo package.
positional arguments:
N an integer for the accumulator
optional arguments:
-h, --help show this help message and exit
-greet Greet Message from Geeks For Geeks.
--sum sum the integers (default: find the max)
$ gfg 5 10 15 -greet
Welcome to GeeksforGeeks!
The Computation Done is Maximum
And Here's your result: 15
$ gfg 5 10 15 -greet --sum
Welcome to GeeksforGeeks!
The Computation Done is Summation
And Here's your result: 30
Reference:
https://python-packaging.readthedocs.io/en/latest/command-line-scripts.html
Similar Reads
Executing Shell Commands with Python
This article starts with a basic introduction to Python shell commands and why one should use them. It also describes the three primary ways to run Python shell commands.os.system()subprocess.run()subprocess.Popen()Â What is a shell in the os?In programming, the shell is a software interface for acce
4 min read
Command Line Interface Programming in Python
This article discusses how you can create a CLI for your python programs using an example in which we make a basic "text file manager". Let us discuss some basics first. What is a Command Line Interface(CLI)? A command-line interface or command language interpreter (CLI), also known as command-line
7 min read
Detect script exit in Python
Python is a scripting language. This means that a Python code is executed line by line with the help of a Python interpreter. When a python interpreter encounters an end-of-file character, it is unable to retrieve any data from the script. This EOF(end-of-file) character is the same as the EOF that
2 min read
Python | Accepting Script Input
A lot of people use Python as a replacement for shell scripts, using it to automate common system tasks, such as manipulating files, configuring systems, and so forth. This article aims to describe accepting Script Input via Redirection, Pipes, or Input Files. Problem - To have a script to be able t
2 min read
Packaging and Publishing Python code
If you have been coding in python, even for a while, you must be familiar with the concept of 'pip' by now. It is a package management system used to install and manage software packages/libraries written in Python. Then one may ask that where are all these packages/libraries stored? It is obvious t
7 min read
Convert Python Script to .exe File
We create lots of Python programs per day and want to share them with the world. It is not that you share that Python program with everyone, and they will run this script in some IDLE shell. But you want everyone to run your executable python script without the installation of Python. So for this wo
4 min read
Python Script to Automate Software Installation
Software installation can often be a time-consuming and monotonous undertaking, particularly when dealing with multiple applications. Python scripting gives a solution by enabling automation of the entire installation process which leads to more time consuming, enhances productivity, and gets rid of
4 min read
Find Installed Python Package Version Using Pip
When working with Python projects, it's important to know which versions of packages are installed in your environment. This helps ensure compatibility, manage dependencies, and troubleshoot issues effectively. Whether you're collaborating on a team, deploying an application, or simply maintaining y
2 min read
code.compile_command() in Python
With the help of code.compile_command() method, we can compile the single or multiple lines of code to check for the syntax error if any by using code.compile_command() method. Syntax : code.compile_command(code) Return : Return the object or compilation error if any. Example #1 : In this example we
1 min read
How To List Installed Python Packages
Working on Python projects may require you to list the installed Python packages in order to manage dependencies, check for updates, or share project requirements with others. In this post, we'll look at numerous techniques for listing the Python packages that are installed on your system.List Insta
5 min read