Python daemon code example

Source: Internet
Author: User

The following is an example of a simple python daemon process. Monitor whether the mailbox capacity is exceeded. If the mailbox capacity exceeds the upper limit, send an email.

The implementation is very simple, just to illustrate how to use python to write daemon. With this, you can handle other complicated daemon processes.

######################################## ######################################## ###################################

Import OS
Import sys

Class Daemonize:
"Create a daemon base class """
Def daemonize (self ):
Try:
# This process wocould create a parent and a child
Pid = OS. fork ()
If pid> 0:
# Take care of the first parent
Sys. exit (0)
Except t OSError, err:
Sys. stderr. write ("Fork 1 has failed --> % d -- [% s] \ n" % (err. errno,
Err. strerror ))
Sys. exit (1)

# Change to root
OS. chdir ('/')
# Detach from terminal
OS. setsid ()
# File to be created?
OS. umask (0)
Try:
# This process creates a parent and a child
Pid = OS. fork ()
If pid> 0:
Print "Daemon process pid % d" % pid
# Bam
Sys. exit (0)
Except t OSError, err:
Sys. stderr. write ("Fork 2 has failed --> % d -- [% s] \ n" % (err. errno,
Err. strerror ))
Sys. exit (1)

Sys. stdout. flush ()
Sys. stderr. flush ()
Def start_daemon (self ):
Self. daemonize ()
Self. run_daemon ()

Def run_daemon (self ):
"Override """
Pass
######################################## ######################################## ###################################

From Daemonize import Daemonize
From email. MIMEText import MIMEText
Import OS
Import smtplib
From smtplib import SMTPException
Import time
Class WatchFile (Daemonize ):

Def _ init _ (self, file_path, size_limit = 15728640 ):
Self. file = OS. path. realpath (file_path)
Print '---'
Assert OS. path. isfile (self. file), '% s does not exist' % self. file
Print '++'
Self. userhome = OS. getenv ('home ')
Self. smtpserver = '* your-host *'
Self. recipient_list = ['recipient @ domain ']
Self. sender = 'sender @ domain'
Self. file_size_limit = size_limit
Self. email_body = OS. path. join (self. userhome, 'email-msg.txt ')
Self. Integer = 3600
Self. log_file = OS. path. join (self. userhome, 'inboxlog.txt ')
Def send_an_email (self ):
"Method to send email to the recipients """
Email_body = open (self. email_body, 'R'). read ()
Msg = MIMEText (email_body)
Msg ['subobject'] = 'your email inbox has exceeded size! '
Msg ['from'] = 'inbox WatchDog'
Msg ['reply-to'] = None
Msg ['to'] = self. recipient_list

Session_obj = smtplib. SMTP ()
Session_obj.connect (self. smtpserver)
Try:
Session_obj.sendmail (self. sender, self. recipient_list, msg. as_string ())
Failed t SMTPException:
Print "Unable to send emails ."
Finally:
Session_obj.close ()
Def watch (self ):
"Method to watch your inbox. This also logs the time when your
Inbox was last checked ."""
Current_file_size = OS. path. getsize (self. file)
If current_file_size> self. file_size_limit:
Self. send_an_email ()
F = open (self. log_file, 'A ')
F. write ('Last checked on: % s' % time. asctime (time. localtime (time. time ())))
F. write ('\ n ')
F. close ()

Def run_daemon (self ):
"Over ridden method from Daemonize. This starts the daemon ."""
While 1:
Self. watch ()
Time. sleep (self. interval)
If _ name _ = '_ main __':
Watchdog = WatchFile ('path-to-your-inbox ')
Watchdog. start_daemon ()
 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.