Simple useful Python Function

Simple useful Python Function

These are functions that I have been useful and flexible to me.

import sys
import subprocess
import string
import socket
import re
import syslog
import smtplib
import os
import sys, getopt
from optparse import OptionParser

# Function that does basic standard output
def message(message):
    sys.stdout.write(message)
    sys.stdout.flush()

#Get command line options then return the variables to be used in other parts of the script.
def CliOptions():
    """
    Setup command-line parsing options
    """
    parser = OptionParser()
    parser.add_option('-o', '--output', default = '',    dest = 'output', help = 'Where to output the file to.')
    parser.add_option('-i', '--input',  default = '',    dest = 'input',  help = 'The Input file.')
    parser.add_option('--TrueOrFalse',	default = False, dest = 'TOF', help = 'True or false value.')
    return parser.parse_args()

#Take the contents of data and write it in a file.
def WriteFile(outputFile, outputInformation): 
    fileHandle = open(outputFile + ".out", "w")
    fileHandle.write(outputInformation)
    fileHandle.close()
 
#Read a file and remove newline and return charaters. Then return the data back.
def readFileFunction(inputFile):
    InputFromFile = []
    with open(inputFile, "r") as ins:
        for inputFileLineItem in ins:
            InputFromFile.append(line.rstrip('\r\n'))
    ins.close()
    return InputFromFile

#Have it output to syslog
def MsgLogging(msg):
	syslog.syslog(syslog.LOG_INFO, msg)

#This function calls shell commands. Clean the output but removing the any newline and return charaters using lambda.
def ExternalCommands(command):
    p1 = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    results = p1.stdout.readlines()

    resultsFromPopen = map(lambda s: s.rstrip('\r\n'), results)
    return resultsFromPopen

How to use the above functions:


#The messaging function:
message ("Hello World\n")

#For the CliOptions function, The function gets called, it getting the commandline arguments. The function will return data into an array.
(options,args) = CliOptions()

#For the msgLogging
MsgLogging("Hello World")

#For ExternalCommands
results = ExternalCommands("ls /")

#For readFileFunction
results = readFileFunction(pathToFile)

#For WriteFile
WriteFile("/tmp/test.txt", "Hello World")

Leave a Reply

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

%d bloggers like this: