Category: Python

Python Code

Working with sqlite in Python

Working with sqlite in Python

#!/bin/python

import datetime
import timedelta
import os.path
import sqlite3
import sys

#Global Variables
DBPath='test.db'

#from datetime import datetime, timedelta
#then = datetime.now() - timedelta(hours = 2)
#now = datetime.now()
#(now - then) > timedelta(days = 1)
#False
#>>> (now - then) > timedelta(hours = 1)
#True

StuffToLoad = [
	(0 , 'example.domain.com'  , 'Maintenance' ,'2014-08-10 15:07:15.067766'),
	(1 , 'example2.doman.com'  , 'Maintenance' ,'2014-08-10 15:07:15.067766'),
	(2 , 'exmaple3.domain.com' , 'Maintenance' ,'2014-08-10 15:07:15.067766'),
]

def CreateDB():
	print "Creating Database....."
	conn = sqlite3.connect(DBPath)
	conn.execute('''CREATE TABLE MInMant (ID INT PRIMARY KEY NOT NULL, Machine TEXT NOT NULL, HostState INT NOT NULL, date CHAR(50))''')
	conn.commit()
	conn.close()

def InsertDB(x):
	conn = sqlite3.connect(DBPath)
	c = conn.cursor()
	t = ('Maintenance',)
	c.execute('SELECT * FROM MInMant WHERE HostState=?', t)
	c.executemany('INSERT INTO MInMant VALUES (?,?,?,?)', StuffToLoad)
	conn.commit()
	conn.close()

def PrintDBContents():
	print "DEBUG PrintDB Contents"
	conn = sqlite3.connect(DBPath)
	c = conn.cursor()
	for row in c.execute('SELECT * FROM MInMant'):
	        print(row)

#We start out program
#if os.path.isfile(DBPath) == 'True':
CreateDB()

#Load data into our DB
InsertDB(StuffToLoad)

#Print data from our DB
PrintDBContents()
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")
%d bloggers like this: