Category: Python

Python Code

Working with sqlite in Python

Working with sqlite in Python


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

#Global Variables

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

StuffToLoad = [
	(0 , ''  , 'Maintenance' ,'2014-08-10 15:07:15.067766'),
	(1 , ''  , 'Maintenance' ,'2014-08-10 15:07:15.067766'),
	(2 , '' , '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))''')

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)

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

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

#Load data into our DB

#Print data from our DB
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):

#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")
#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:
    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: