Friday, February 6, 2015

Python - Basic Template

In my first post about python, I was talking about parsing huge text files with python regular expression. I thought I should share the basic template kind of set up that I have for myself to save some time while scripting. I use this basic template in writing some quick script for immediate needs. It really saves my time.

I have commented then and there in the script to increase the readability of the script. As said in every programming books, commenting your code is a must do activity and it will help anyone to understand the script in better way.






So, here is the template sort of thing I talked about

#import statements
import os
import sys

"""function main holds the base logic and validation. Put your base logic here and input validation"""

def main(argv):
 if len(argv)==1:
 # put your base logic here
 else:
  usage()

"""This prints the usage of the script when input is not provided as excepted or input not in proper context"""

def usage():
 print 'usage of the script and example inputs'

"""boilerplate template - it invokes main function and it is the starting point of the
script"""

if __name__ == "__main__":
 main(sys.argv[1:])


Let me now write a simple python script using this template sort of thing. Let's consider the problem statement of executing a shell command through python. This should give you the same result what you see when you run the shell command at terminal


#import statements
import os
import sys
import commands

"""function main holds the base logic and validation. Put your base logic here
and input validation
This function will execute the command received as input and returns the result"""

def main(argv):
 if len(argv)==1:
  command = argv[0]
  status,output=commands.getstatusoutput(command)
  if status==0:
   print output
  else:
   print 'syserr: '+str(status)+'-'+output
 else:
  usage()

"""This prints the usage of the script when input is not provided as excepted or input not in proper context"""

def usage():
 print 'Usage: python cmdExecute.py "command"'

"""boilerplate template - it invokes main function and it is the starting point of the 
script"""

if __name__ == "__main__":
 main(sys.argv[1:])


In this above script I have imported commands module to perform command execution and included the base logic in main function which execute's the command and gets the result. I have added script usage comments in usage function and finally added additional comments as needed.


Thanks for reading

Cheers!


No comments:

Post a Comment