DEV Community

Cover image for How to make a CLI application in python
souvik
souvik

Posted on

How to make a CLI application in python

Create an express-generator application of our own.

We will use python and docopt to create a CLI application.

Step 1:

  • Install docopt.

pip install docopt

To know more about docopt here.

Step 2:

  • To use docopt we need to create a docstring in python
'''create-express-app.
Usage:
    create-express-app.py (-h | --help)
    create-express-app.py --version
    create-express-app.py check 
    create-express-app.py create <params>
Options:
    -h --help   Show this screen
    --version   Show Version 
'''

Step 3:

  • Now all we have to do is to import docopt and parse the input
from docopt import docopt 
if __name__ == '__main__':
   arguments = docopt(__doc__,version='1.0.0')
   print(arguments)

Step 4:

  • Now we have to write functions to handle the parsed inputs

The arguments variable returns a dictionary
we can then check for the command we are looking and perform the function

if arguments['check'] == True:
        check()
    elif arguments['create'] == True:
        create(arguments['<params>'])

The create function :

def create(params):
    import os 
    import subprocess
    os.mkdir(params)
    path = './'+params
    os.chdir(path)
    os.system("npm init -y")
    os.system("type nul > app.js")
    os.system("npm i express body-parser")
    os.system("code ..")

In the create function we are building the project to do the following task:

  • run npm init
  • Create a file named app.js
  • install the express and body-parser npm packages
  • and open the directory in visual studio code.

To check out the complete code here

Top comments (0)