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 <file.py>
    • In this case we would like to run our program on linux machine by using file.py
  • Scenario:
    • Build a calculator for additions add.py 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 [‘filename.py’, ‘arg0’, ‘arg1’…..]
  • To get only positional arguments using python list slicing sys.argv[1::]
  • Sample
#!/usr/bin/python
import sys

# calc.py 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':
        print(addition(sys.argv[2::]))
    elif operation == 'mul':
        print(multiply(sys.argv[2::]))
    else:
        print("invalid arguments enter calc.py add args or calc.py mul args")
        exit(1)

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

Exercise:

  • Write a python code to set and get environment variables.
envr.py set JAVA_HOME  /opt/lib/jav/home

envr.py get PATH

envr.py get-all
  • Refer python module os

By continuous learner

devops & cloud enthusiastic learner

Leave a ReplyCancel reply

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

Please turn AdBlock off
Social Network Integration by Acurax Social Media Branding Company

Discover more from Direct DevOps from Quality Thought

Subscribe now to keep reading and get access to the full archive.

Continue reading

Exit mobile version
%%footer%%