Python Classroom Series – 30/Nov/2019

Command line Parsing using python.

  • Intention:
    • To create a python program which can be used as command line
    • To run python program we use syntax python <>
    • In this case we would like to run our program on linux machine by using
  • Scenario:
    • Build a calculator for additions 1 2 3
  • Special variable in python:
    • __name__: This variable will have value of __main__ if called from command line

Parsing Arguments using sys.argv

  • sys.argv will return a list with [‘’, ‘arg0’, ‘arg1’…..]
  • To get only positional arguments using python list slicing sys.argv[1::]
  • Sample
import sys

# add/mul  10 20 30

def multiply(args):
    result = 1
    for argument in args:
        result = result * int(argument)
    return result

def addition(args):
    result = 0
    for argument in args:
        result = result + int(argument)
    return result

if __name__ == '__main__':
    operation = sys.argv[1]
    if operation == 'add':
    elif operation == 'mul':
        print("invalid arguments enter add args or mul args")

Classes and Objects

  • Object:
    • Capabilities:
      • What it can do
    • Contents:
      • What it has
  • Examples:
    • Laptop:
      • Capabilities: Browsing, LoadOs, InstallSofware
      • Contents: Keyboard, RAM, Processor …..
    • BankAccount:
      • Capabilities: Deposit, Withdraw, Open, Close
      • Contents: Accountno, Bank name, Branch…
  • Capabilities will become Methods
  • Contents will become Members


  • Write a python code to set and get environment variables. set JAVA_HOME  /opt/lib/jav/home get PATH get-all
  • Refer python module os

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner