Python
Last edited September 20, 2008
More by {joey} »
My super-duper python daemon

My super-duper Python Daemon code (daemon.py):

'''
    This module is used to fork the current process into a daemon.
    Almost none of this is necessary (or advisable) if your daemon
    is being started by inetd. In that case, stdin, stdout and stderr are
    all set up for you to refer to the network connection, and the fork()s
    and session manipulation should not be done (to avoid confusing inetd).
    Only the chdir() and umask() steps remain as useful.
    References:
        UNIX Programming FAQ
            1.7 How do I get my program to act like a daemon?
                http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
        Advanced Programming in the Unix Environment
            W. Richard Stevens, 1992, Addison-Wesley, ISBN 0-201-56317-7.

    History:
      2001/07/10 by Jurgen Hermann
      2002/08/28 by Noah Spurrier
      2003/02/24 by Clark Evans
      2007/03/20 by Yusuf Kaka
     
      http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012
'''
USERPROG = test
LOGFILE = '/var/log/appd.log'
PIDFILE = '/var/run/appd.pid'
keepalive = True
numOfrestarts = 10 # Number of allowed restarts per day
delayBetRest = 30 #seconds

import sys, os, time
from signal import SIGTERM

def deamonize(stdout='/dev/null', stderr=None, stdin='/dev/null',
              pidfile=None, startmsg = 'started with pid %s' ):
    '''
        This forks the current process into a daemon.
        The stdin, stdout, and stderr arguments are file names that
        will be opened and be used to replace the standard file descriptors
        in sys.stdin, sys.stdout, and sys.stderr.
        These arguments are optional and default to /dev/null.
        Note that stderr is opened unbuffered, so
        if it shares a file with stdout then interleaved output
        may not appear in the order that you expect.
    '''
    # Do first fork.
    try:
        pid = os.fork()
        if pid > 0: sys.exit(0) # Exit first parent.
    except OSError, e:
        sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
        sys.exit(1)
       
    # Decouple from parent environment.
    os.chdir("/")
    os.umask(0)
    os.setsid()
   
    # Do second fork.
    try:
        pid = os.fork()
        if pid > 0: sys.exit(0) # Exit second parent.
    except OSError, e:
        sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
        sys.exit(1)
   
    # Open file descriptors and print start message
    if not stderr: stderr = stdout
    si = file(stdin, 'r')
    so = file(stdout, 'a+')
    se = file(stderr, 'a+', 0)
    pid = str(os.getpid())
    sys.stderr.write("\n%s\n" % startmsg % pid)
    sys.stderr.flush()
    if pidfile: file(pidfile,'w+').write("%s\n" % pid)
   
    # Redirect standard file descriptors.
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())

def startstop(stdout='/dev/null', stderr=None, stdin='/dev/null',
              pidfile='pid.txt', startmsg = 'started with pid %s', action='start' ):
    if action:
        try:
            pf  = file(pidfile,'r')
            pid = int(pf.read().strip())
            pf.close()
            os.getpgid(pid)
        except IOError:
            pid = None
        except OSError:
            os.remove(pidfile)
            pid = None 
        if 'stop' == action or 'restart' == action:
            if not pid:
                mess = "Could not stop, pid file '%s' missing.\n"
                sys.stderr.write(mess % pidfile)
                if 'stop' == action:
                    sys.exit(1)
                action = 'start'
                pid = None
            else:
               try:
                  while 1:
                      os.kill(pid,SIGTERM)
                      time.sleep(1)
               except OSError, err:
                  err = str(err)
                  if err.find("No such process") > 0:
                      os.remove(pidfile)
                      if 'stop' == action:
                          sys.exit(0)
                      action = 'start'
                      pid = None
                  else:
                      print str(err)
                      sys.exit(1)
       
        if 'start' == action:
            if pid:
                mess = "Start aborded since pid file '%s' exists.\n"
                sys.stderr.write(mess % pidfile)
                sys.exit(1)

            deamonize(stdout,stderr,stdin,pidfile,startmsg)
            return

        if 'status' == action:
            if not pid:
                sys.stderr.write('Status: Stopped\n')

            else: sys.stderr.write('Status: Running\n')
            sys.exit(0)

def test():
    '''
        This is an example main function run by the daemon.
        This prints a count and timestamp once per second.
    '''
    sys.stdout.write ('Message to stdout...')
    sys.stderr.write ('Message to stderr...')
    c = 0
    while 1:
        sys.stdout.write ('%d: %s\n' % (c, time.ctime(time.time())) )
        sys.stdout.flush()
        c = c + 1
        time.sleep(1)

if __name__ == "__main__":
    startstop(stdout=LOGFILE,
              pidfile=PIDFILE)
    restartCount = 0
    lastStart = time.time()
    try:
        USERPROG()
    except:
        if keepalive: sys.stderr.write("Application broke, restarting...")
        else: sys.stderr.write("Application broke, not restarting")
    while keepalive:
        time.sleep(delayBetRest)
        if time.time() - lastStart > 86400:
            lastStart = time.time()
            restartCount = 0
        restartCount += 1
        if restartCount > numOfrestarts:
            keepalive = False
        try:
            USERPROG()
        except:
            sys.stderr.write("Application broke, restarting...")



and the /etc/init.d/ shellscript to go with it:

#! /bin/sh
# example python daemon starter script
# based on skeleton from Debian GNU/Linux
# cliechti@gmx.net
# place the daemon scripts in a folder accessible by root. /usr/local/sbin is a good idea

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/local/sbin/daemon.py
NAME=pydaemon
DESC="Example daemon"

test -f $DAEMON || exit 0

set -e

case "$1" in
  start)
    echo -n "Starting $DESC: "
    #start-stop-daemon --start --quiet --pidfile /var/run/$NAME.pid \
    #    --exec $DAEMON
    $DAEMON start
    echo "$NAME."
    ;;
  stop)
    echo -n "Stopping $DESC: "
    #start-stop-daemon --stop --quiet --pidfile /var/run/$NAME.pid
    # \    --exec $DAEMON
    $DAEMON stop
    echo "$NAME."
    ;;
  #reload)
    #
    #    If the daemon can reload its config files on the fly
    #    for example by sending it SIGHUP, do it here.
    #
    #    If the daemon responds to changes in its config file
    #    directly anyway, make this a do-nothing entry.
    #
    # echo "Reloading $DESC configuration files."
    # start-stop-daemon --stop --signal 1 --quiet --pidfile \
    #    /var/run/$NAME.pid --exec $DAEMON
  #;;
  restart|force-reload)
    #
    #    If the "reload" option is implemented, move the "force-reload"
    #    option to the "reload" entry above. If not, "force-reload" is
    #    just the same as "restart".
    #
    echo -n "Restarting $DESC: "
    #start-stop-daemon --stop --quiet --pidfile \
    #    /var/run/$NAME.pid
        # --exec $DAEMON
    #sleep 1
    #start-stop-daemon --start --quiet --pidfile \
    #    /var/run/$NAME.pid --exec $DAEMON
    $DAEMON restart
    echo "$NAME."
    ;;
  *)
    N=/etc/init.d/$NAME
    $DAEMON status
    # echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
    echo "Usage: $N {start|stop|restart|force-reload}" >&2
    exit 1
    ;;
esac

exit 0



Basic IO

x=raw_input("Name:")
print("Hello "+x+"\nHope you enjoy studying python")
File Handling

logfile = open('test.log', 'a')
logfile.write('Hello')
logfile.close()
print file('test.log').read()
CGI

#!/usr/bin/python
import cgitb
cgitb.enable()

print "Content-type: text/html"
print

import time

print "<HTML>"
print "<HEAD>"
print "<TITLE>Penzilla.net:  What is the Time? Example</TITLE>"
print "</HEAD>"
print "<BODY>"
print "<H2>Penzilla.net What is the Time?(wittime.py) Example:</h2>"
print "<P>Penzilla thinks that it is: %s</P>" % time.ctime()
print "</BODY>"
print "</HTML>"
 
OS Commands

import os

print(os.system('date'))

f=os.popen('date')
print f.readline()

os.execl("/usr/bin/gedit") 

Convert jpg to animated gif!
for k in range(22,45):
    os.system("convert -delay 400 GDT"+str(k)+"*.jpg GDT"+str(k)+".gif")
    print k
XML RPC

import xmlrpclib,socket

def do_rpc(host,port,path,method,arguments):
    params = xmlrpclib.dumps(arguments)
    CONTENT="<?xml version='1.0'?>\n<methodCall>\n<methodName>"+method+"</methodName>\n"+params+"</methodCall>\n"
    #print CONTENT
    length=len(CONTENT)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    s.send("POST "+path+" HTTP/1.0\r\n")
    s.send("Content-Type: text/xml\r\n")
    s.send("Content-Length: "+str(length)+"\r\n\r\n")
    s.send(CONTENT)
    datarecv=s.recv(1024)
    #print "Reply Received: "+ str(datarecv)
    response=str(datarecv)
    theXML=response[response.find("<?xml"):]
    values=xmlrpclib.loads(theXML)[0][0]
    s.close()
    return values
Regular Expressions

import re
rc=open("/etc/resolv.conf")
for line in rc:
    match =  re.match("nameserver\s+(\d{1,3}\.\d{1,3}.\d{1,3}.\d{1,3})+.+",line)
    if match:
        print match.group(1)
Threads

import threading

class MyRPC (threading.Thread):
 def __init__ (self):
Thread.__init__(self)

    def run(self): 
    doSumthing()


try:
       MyRPC().start() 
except:
       print "can't start thread"


def method():
    ....


cbThread = threading.Thread(target = method)
cbThread.start()
Sockets

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.connect((host, port))
except:
     print("socket error") 
socket.send("POST "+path+" HTTP/1.0\r\n")
socket.close()
import sys
param = sys.arg[0]
Get IP
 
import socket
socket.gethostbyname(socket.gethostname())
socket.gethostbyname_ex(socket.gethostname())
XML Parsing

self.m_pairs={"Tag1":"","Tag2":""}
    def parseMessage(self,message):
        try:
            xmldoc = minidom.parseString(message)
        except:
            print("Parse error!")
            print message
            return False
        for i,j in self.m_pairs.iteritems():
               self.m_pairs[i] = xmldoc.getElementsByTagName(self.m_root)[0].getAttribute(i)
        return True
XML Encoding

from xml.dom import minidom

def generateMessage(self):
        impl = minidom.DOMImplementation()
        doc = impl.createDocument(None, self.m_name, None)#None, "test", None)
        root = doc.createElement(self.m_root)
        # Create element


        for i,j in self.m_pairs.iteritems():
            if i[:6]=="CHILD_":
                item = doc.createElement(self.m_child)
                #item.setAttribute(i[6:],j)
                root.appendChild(item)
            else:
                root.setAttribute(i,j)           
               
        # Add Root to Document
        doc.documentElement.appendChild(root)

        # Serialize the output
        m_serialout=doc.toxml(encoding="ISO-8859-1")
        m_serialout = m_serialout[:m_serialout.find("?>")+2]+m_serialout[m_serialout.find("<"+self.m_root):m_serialout.find("</Uxml")]
        #m_serialout = doc.toprettyxml()#getDocumentElement().toString()
        return m_serialout
     
Closing Applications Gracefully

import sys
try:
   while 1:
      print "Running...."
except KeyboardInterrupt:
    print "Closing..."
    sys.exit(1)
Obtaining the variable type

if isinstance(self.result,str):
    outp+=self.result
elif isinstance(self.result,int):
    outp+=str(self.result)
else:
    for i,j in self.result.iteritems():
        outp+="\n"+i+": "+j
Overiding a method

class testclass:
    def __init__(self):
        self.cow = "something to say"
    def amethod(self):
        print "nothing to say?"
       

class testclass2(testclass):
    def amethod(self):
        print self.cow
       
testclass.amethod = testclass2.amethod      
myinstance = testclass()
myinstance.amethod()
 
Python for Series 60

import contacts
db=contacts.open()
s=db.find('yusuf')
contact=s[0]
number=s.find('mobile_number')[0].value
number= u'*198*1*1*'+number+u'#'
import telephone
telephone.dial(number) 
Binary to Hex convertor

Word Aligned - category python
blog.wordaligned.org/articles/category/python
#!/usr/bin/env python
Reads binary data from stdin and converts it into comma separated hex numbers (suitable e.g. for inclusion in an array initialiser) written to stdout.

import sys, textwrap
print
"\n".join(textwrap.wrap( ", ".join("0x%02x" % ord(b) for b in sys.stdin.read())))
The content on this page is provided by a Google Notebook user, and Google assumes no responsibility for this content.