David Learns Programming


Currently working on Core Python by Wesley Chun.
Join us as we study as a group.
Please visit PythonGroup for more info.


Bash printf in color

Bash print color text.

Rather than using obfuscated escape sequences, use the tput facility instead. Here is an excerpt from my ~/.bashrc that I use for my PS1 prompt:

 
BLACK=$(tput setaf 0)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
LIME_YELLOW=$(tput setaf 190)
POWDER_BLUE=$(tput setaf 153)
BLUE=$(tput setaf 4)
MAGENTA=$(tput setaf 5)
CYAN=$(tput setaf 6)
WHITE=$(tput setaf 7)
BRIGHT=$(tput bold)
NORMAL=$(tput sgr0)
BLINK=$(tput blink)
REVERSE=$(tput smso)
UNDERLINE=$(tput smul)

To reset the color information such that subsequent text is in the normal terminal color you would append ${NORMAL} to the end like so:

echo "${RED}this is red ${NORMAL}this is normal"

emerge a list of packages from a text file

#!/usr/bin/python
import subprocess
 
def merge(package):
    mymerge = "emerge"
    eopt = "-p"
    subprocess.call([mymerge, eopt, package])
 
fobj = "packages.txt"
FILE = open(fobj, "r")
for package in FILE:
    merge(package)
FILE.close()

packages.txt
virtual/perl-CGI
virtual/perl-Class-ISA
virtual/perl-Compress-Raw-Bzip2
virtual/perl-Compress-Raw-Zlib
virtual/perl-File-Spec
virtual/perl-IO-Compress
virtual/perl-IO-Zlib
virtual/perl-Locale-Maketext-Simple
virtual/perl-Pod-Simple
virtual/perl-Scalar-List-Utils
virtual/perl-Text-Balanced
virtual/perl-version
perl-core/CGI
perl-core/Class-ISA
perl-core/Compress-Raw-Bzip2
perl-core/Compress-Raw-Zlib
perl-core/File-Spec
perl-core/IO-Compress
perl-core/IO-Zlib
perl-core/Locale-Maketext-Simple
perl-core/Pod-Simple
perl-core/Scalar-List-Utils
perl-core/Text-Balanced
perl-core/version

wxPython Login Dict

#!/usr/bin/python
# Filename: wx_login.py
# Author : comprookie
import wx
import time
import datetime
import cPickle
import os
 
class MainWindow(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(400,200), style = wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE)
 
        #-- I think you need a panel if you're going to have more than one control in your frame.
        panel = wx.Panel(self, -1)
 
        #--- Create the Username label and text box and add them to the panel
        #--- I think the TextCtrl needs to have self. at the front for the value to be used by
        #--- the Process() function below.  There must be a better way.
 
        self.txt_Username = wx.TextCtrl(panel, 1, size=(150, -1))
        lbl_Username = wx.StaticText(panel, -1, "Username:")
 
        #-- Create the password label and text box and add them to the panel
        self.txt_Password = wx.TextCtrl(panel, 1, size=(150, -1), style=wx.TE_PASSWORD)
        lbl_Password = wx.StaticText(panel, -1, "Password:")
 
        #-- Create the processing button, add it to the panel and wire it up to a function in the class
        btn_Process = wx.Button(panel, -1, "&Login")
        self.Bind(wx.EVT_BUTTON, self.Process, btn_Process)
 
        #-- Create the close button, add it to the panel and wire it up to a function in the class
        btn_Close = wx.Button(panel, -1, "&Close")
        self.Bind(wx.EVT_BUTTON, self.onExit, btn_Close)
 
        #-- Now we have to create a grid to layout our controls
        #format--> sizer.Add(widget_to_add, proportion,spacing btn widgets )
        #Also using Flexigrid sizer use AddMany for simplicity
        sizer = wx.FlexGridSizer(rows=3, cols=2, hgap=5, vgap=15)
        sizer.Add(lbl_Username,0, wx.LEFT|wx.TOP| wx.RIGHT, 50)
        sizer.Add(self.txt_Username,0, wx.TOP| wx.RIGHT, 50)
        sizer.Add(lbl_Password,0, wx.LEFT|wx.RIGHT, 50)
        sizer.Add(self.txt_Password,0, wx.RIGHT, 50)
        sizer.Add(btn_Process,0, wx.LEFT, 50)
        sizer.Add(btn_Close,0, wx.LEFT, 75) 
        #-- Add the grid to the panel and make it fit
        panel.SetSizer(sizer)
 
        #-- Show the window that we've just built
        self.Show(True)
 
    def Process(self, event):
        UserText = self.txt_Username.GetValue()
        PasswordText = self.txt_Password.GetValue()
        time_stamp = time.strftime('%Y-%m-%d-%I:%M:%S %p', time.localtime())
        if db.has_key(UserText):
            for k, v, in db.iteritems():
                u_msg = "Your username is: %s" %  (k)
                p_msg = "Your password is: %s" %  (v[0])
                t_msg = "Your last login was: %s" %  (v[1])
                welcome = "Welcome Back %s" % (k)
                wp = wx.MessageDialog(self, welcome, "Welcome", wx.OK | wx.ICON_INFORMATION)
                wp.ShowModal()
                wp.Destroy()
                tp = wx.MessageDialog(self, t_msg, "Back", wx.OK | wx.ICON_INFORMATION)
                tp.ShowModal()
                tp.Destroy()
        else:
            db[UserText] = PasswordText, time_stamp
            for k, v, in db.iteritems():
                u_msg = "Your username is: %s" %  (k)
                p_msg = "Your password is: %s" %  (v[0])
                t_msg = "Your last login was: %s" %  (v[1])
                dt = wx.MessageDialog(self, t_msg, "Timestamp", wx.OK | wx.ICON_INFORMATION)
                dt.ShowModal()
                dt.Destroy()
                du = wx.MessageDialog(self, u_msg, "Username", wx.OK | wx.ICON_INFORMATION)
                du.ShowModal()
                du.Destroy()
                dp = wx.MessageDialog(self, p_msg, "Password", wx.OK | wx.ICON_INFORMATION)
                dp.ShowModal()
                dp.Destroy()
 
    def onExit(self, event):
        self.Close(True)
 
if __name__ == '__main__':
    fname = 'login_db.dat'
    if os.path.exists(fname):
        try:
            fobj = open(fname, 'rb')
            data = cPickle.Unpickler(fobj)
            db = data.load()
        finally:
            fobj.close()
    else:
        db = {}
    app = wx.PySimpleApp()
    frame = MainWindow(None,-1,"Enter Credentials")
    app.MainLoop()
    def dump_db(db):
        fname = open('login_db.dat', 'w')
        object = cPickle.Pickler(fname)
        object.dump(db)
        fname.close()
    dump_db(db)

Daily Motivation Mailer

#!/bin/bash
#store todays daily reading
url=http://www.hazelden.org/web/public/thought.view?defaultCatId=1901
lynx -dump -nolist $url | tail -n 80 | head -28 > today_thought.txt
 
#requires: basename,date,md5sum,sed,sendmail,uuencode
function fappend {
    echo "$2">>$1;
}
YYYYMMDD=`date +%Y%m%d`
 
# CHANGE THESE
TOEMAIL="david@bellsouth.net, <a href="mailto:david@linux.com">david@linux.com</a>, comp@gmail.com";
FREMAIL="david@dwabbott.com";
SUBJECT="Thought for the Day - $YYYYMMDD";
MSGBODY="Hello this is your Thought for the Day";
ATTACHMENT="today_thought.txt"
MIMETYPE="text/plain" #if not sure, use <a href="http://www.webmaster-toolkit.com/mime-types.shtml</p>
<p>#" title="http://www.webmaster-toolkit.com/mime-types.shtml</p>
<p>#">http://www.webmaster-toolkit.com/mime-types.shtml</p>
<p>#</p></a> DON'T CHANGE ANYTHING BELOW
TMP="/tmp/tmpfil_123"$RANDOM;
BOUNDARY=`date +%s|md5sum`
BOUNDARY=${BOUNDARY:0:32}
FILENAME=`basename $ATTACHMENT`
 
rm -rf $TMP;
cat $ATTACHMENT|uuencode --base64 $FILENAME>$TMP;
sed -i -e '1,1d' -e '$d' $TMP;#removes first & last lines from $TMP
DATA=`cat $TMP`
 
rm -rf $TMP;
fappend $TMP "From: $FREMAIL";
fappend $TMP "To: $TOEMAIL";
fappend $TMP "Reply-To: $FREMAIL";
fappend $TMP "Subject: $SUBJECT";
fappend $TMP "Content-Type: multipart/mixed; boundary=\""$BOUNDARY"\"";
fappend $TMP "";
fappend $TMP "This is a MIME formatted message.  If you see this text it means that your";
fappend $TMP "email software does not support MIME formatted messages.";
fappend $TMP "";
fappend $TMP "--$BOUNDARY";
fappend $TMP "Content-Type: text/plain; charset=ISO-8859-1; format=flowed";
fappend $TMP "Content-Transfer-Encoding: 7bit";
fappend $TMP "Content-Disposition: inline";
fappend $TMP "";
fappend $TMP "$MSGBODY";
fappend $TMP "";
fappend $TMP "";
fappend $TMP "--$BOUNDARY";
fappend $TMP "Content-Type: $MIMETYPE; name=\"$FILENAME\"";
fappend $TMP "Content-Transfer-Encoding: base64";
fappend $TMP "Content-Disposition: attachment; filename=\"$FILENAME\";";
fappend $TMP "";
fappend $TMP "$DATA";
fappend $TMP "";
fappend $TMP "";
fappend $TMP "--$BOUNDARY--";
fappend $TMP "";
fappend $TMP "";
#cat $TMP>out.txt
cat $TMP|/usr/sbin/sendmail -t;
rm $TMP;

Motion Log Cleanup

#!/bin/bash
# Clean Motion .jpg .avi files
 
LOG_DIR=/var/log/motion
ROOT_UID=0   # Must be root to remove files
E_XCD=86     # Can't change directory?
E_NOTROOT=87 # Non root exit error
 
# As root
if [ "$UID" -ne "$ROOT_UID" ]
then
    echo "MUST be root to delete motion files."
    exit $E_NOTROOT
fi
 
cd $LOG_DIR || {
    echo "Cannot change to $LOG_DIR" >&2
    exit $E_XCD;
}
 
rm -f *.jpg
echo "All .jpg files deleted."
rm -f *.avi
echo "All .avi files deleted."
 
exit 0