Open In App
Related Articles

Command Line Scripts | Python Packaging

Improve Article
Save Article
Like Article

How do we execute any script in Python?

$ python
$ python 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:

  1. Create your Command Line Script.
  2. Set-up files and folder structure for Packaging.
  3. Modify your file to incorporate your CLI scripts.
  4. Test your package before publishing and then Build.
  5. Upload on pypi and publish your package.
  6. 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

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")
            print("The Computation Done is Summation")
        print("And Here's your result:", end =" ")   

Step #2: Set-up files and folder Structure

Step #3: Modify 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!

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.'
        name ='vibhu4gfg',
        version ='1.0.0',
        author ='Vibhu Agarwal',
        author_email ='',
        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 file.
Install your intended package by typing in this command.

$ python3 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 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


$ 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


Last Updated : 29 Apr, 2019
Like Article
Save Article
Similar Reads
Related Tutorials