]> kaliko git repositories - python-daemon.git/commitdiff
Python3 conversion
authorkaliko <efrim@azylum.org>
Sun, 25 Nov 2012 13:16:14 +0000 (14:16 +0100)
committerkaliko <kaliko@azylum.org>
Tue, 27 Nov 2012 18:51:54 +0000 (19:51 +0100)
doc/examples/daemon-example.py
seth.py

index 47dff70241296913c9961d024a93bbac45743fa9..bb1855b78d555e01837b83463c5cf77994b8b5a1 100755 (executable)
@@ -11,15 +11,17 @@ class MyDaemon(Daemon):
     def run(self):
         """Overrides Daemon().run() with actions you want to daemonize.
         MyDaemon.run() is then called within MyDaemon().start()"""
     def run(self):
         """Overrides Daemon().run() with actions you want to daemonize.
         MyDaemon.run() is then called within MyDaemon().start()"""
-        print "Starting Deamon!"
+        print('Starting Deamon!')  # message issued on self.stdout
         while True:
             time.sleep(1)
         while True:
             time.sleep(1)
+            sys.stderr.write('œ unicode write test to stderr\n')
+            sys.stdout.write('write test to stdout\n')
 
     def shutdown(self):
         """Overrides Daemon().shutdown() with some clean up"""
 
     def shutdown(self):
         """Overrides Daemon().shutdown() with some clean up"""
-        print "Stopping Daemon!"
+        print("Stopping Daemon!")  # message issued on self.stdout
 
 
-if __name__ == "__main__":
+if __name__ == '__main__':
     daemon = MyDaemon('/tmp/daemon-example.pid',
             '/tmp/daemon.log')
     if len(sys.argv) == 2:
     daemon = MyDaemon('/tmp/daemon-example.pid',
             '/tmp/daemon.log')
     if len(sys.argv) == 2:
@@ -30,9 +32,9 @@ if __name__ == "__main__":
         elif 'restart' == sys.argv[1]:
             daemon.restart()
         else:
         elif 'restart' == sys.argv[1]:
             daemon.restart()
         else:
-            print "Unknown command"
+            print('Unknown command')
             sys.exit(2)
         sys.exit(0)
     else:
             sys.exit(2)
         sys.exit(0)
     else:
-        print "usage: %s start|stop|restart" % sys.argv[0]
+        print("usage: {} start|stop|restart".format(sys.argv[0]))
         sys.exit(2)
         sys.exit(2)
diff --git a/seth.py b/seth.py
index cfc5ed421ed1fb235c361ad385cd6eda63ab499d..77f7a4b9810c0010dd0931f2d58c23a60fa65d3c 100644 (file)
--- a/seth.py
+++ b/seth.py
@@ -19,13 +19,20 @@ class Daemon(object):
     A generic daemon class.
 
     Usage: subclass the Daemon class and override the run() method
     A generic daemon class.
 
     Usage: subclass the Daemon class and override the run() method
+
+        Daemon([pidfile[, stdin[, stdout[, stderr]]]])
+
+            pidfile : file to write pid to (default no pid file writen)
+            stdin   : standard input file descriptor (default to /dev/null)
+            stdout  : standard output file descriptor (default to /dev/null)
+            stderr  : standard error file descriptorr (default to /dev/null)
     """
     """
-    version = "0.5"
+    version = '0.5'
 
     def __init__(self, pidfile,
 
     def __init__(self, pidfile,
-            stdin='/dev/null',
-            stdout='/dev/null',
-            stderr='/dev/null'):
+            stdin = os.devnull,
+            stdout = os.devnull,
+            stderr = os.devnull):
         self.stdin = stdin
         self.stdout = stdout
         self.stderr = stderr
         self.stdin = stdin
         self.stdout = stdout
         self.stderr = stderr
@@ -49,8 +56,8 @@ class Daemon(object):
             if pid > 0:
                 # exit first parent
                 sys.exit(0)
             if pid > 0:
                 # exit first parent
                 sys.exit(0)
-        except OSError, e:
-            sys.stderr.write('fork #1 failed: %d (%s)\n' % (e.errno, e.strerror))
+        except OSError as e:
+            sys.stderr.write('fork #1 failed: {0.errno:d} ({0.strerror})\n'.format(e))
             sys.exit(1)
 
         # Decouple from parent environment
             sys.exit(1)
 
         # Decouple from parent environment
@@ -64,17 +71,18 @@ class Daemon(object):
             if pid > 0:
                 # exit from second parent
                 sys.exit(0)
             if pid > 0:
                 # exit from second parent
                 sys.exit(0)
-        except OSError, e:
-            sys.stderr.write('fork #2 failed: %d (%s)\n' % (e.errno, e.strerror))
+        except OSError as e:
+            sys.stderr.write('fork #2 failed: {0.errno:d} ({0.strerror})\n'.format(e))
             sys.exit(1)
 
         self.write_pid()
         # redirect standard file descriptors
         sys.stdout.flush()
         sys.stderr.flush()
             sys.exit(1)
 
         self.write_pid()
         # redirect standard file descriptors
         sys.stdout.flush()
         sys.stderr.flush()
-        si = file(self.stdin, 'r')
-        so = file(self.stdout, 'a+')
-        se = file(self.stderr, 'a+', 0)
+        # TODO: binary or txt mode?
+        si = open(self.stdin,  mode='rb')
+        so = open(self.stdout, mode='ab+')
+        se = open(self.stderr, mode='ab+', buffering=0)
         os.dup2(si.fileno(), sys.stdin.fileno())
         os.dup2(so.fileno(), sys.stdout.fileno())
         os.dup2(se.fileno(), sys.stderr.fileno())
         os.dup2(si.fileno(), sys.stdin.fileno())
         os.dup2(so.fileno(), sys.stdout.fileno())
         os.dup2(se.fileno(), sys.stderr.fileno())
@@ -89,26 +97,28 @@ class Daemon(object):
         pid = str(os.getpid())
         try:
             os.umask(self.umask)
         pid = str(os.getpid())
         try:
             os.umask(self.umask)
-            file(self.pidfile, 'w').write('%s\n' % pid)
-        except Exception, wpid_err:
-            sys.stderr.write(u'Error trying to write pid file: %s\n' % wpid_err)
+            open(self.pidfile, 'w').write('%s\n' % pid)
+        except Exception as wpid_err:
+            sys.stderr.write('Error trying to write pid file: {}\n'.format(wpid_err))
             sys.exit(1)
         os.umask(0)
         atexit.register(self.delpid)
 
     def signal_management(self):
             sys.exit(1)
         os.umask(0)
         atexit.register(self.delpid)
 
     def signal_management(self):
-        # Declare signal handlers
+        """Declare signal handlers
+        """
         signal(SIGTERM, self.exit_handler)
 
     def exit_handler(self, signum, frame):
         sys.exit(1)
 
     def delpid(self):
         signal(SIGTERM, self.exit_handler)
 
     def exit_handler(self, signum, frame):
         sys.exit(1)
 
     def delpid(self):
+        """Remove PID file"""
         try:
             os.unlink(self.pidfile)
         except OSError as err:
         try:
             os.unlink(self.pidfile)
         except OSError as err:
-            message = 'Error trying to remove PID file: %s\n'
-            sys.stderr.write(message % err)
+            message = 'Error trying to remove PID file: {}\n'
+            sys.stderr.write(message.format(err))
 
     def start(self):
         """
 
     def start(self):
         """
@@ -116,15 +126,15 @@ class Daemon(object):
         """
         # Check for a pidfile to see if the daemon already runs
         try:
         """
         # Check for a pidfile to see if the daemon already runs
         try:
-            pf = file(self.pidfile, 'r')
+            pf = open(self.pidfile, 'r')
             pid = int(pf.read().strip())
             pf.close()
         except IOError:
             pid = None
 
         if pid:
             pid = int(pf.read().strip())
             pf.close()
         except IOError:
             pid = None
 
         if pid:
-            message = 'pidfile %s already exist. Daemon already running?\n'
-            sys.stderr.write(message % self.pidfile)
+            message = 'pidfile {0.pidfile} already exist. Daemon already running?\n'
+            sys.stderr.write(message.format(self))
             sys.exit(1)
 
         # Start the daemon
             sys.exit(1)
 
         # Start the daemon
@@ -143,28 +153,28 @@ class Daemon(object):
         """
         Stop the daemon
         """
         """
         Stop the daemon
         """
-        # Get the pid from the pidfile
+        # Get the pid from the pidopen
         try:
         try:
-            pf = file(self.pidfile, 'r')
+            pf = open(self.pidfile, 'r')
             pid = int(pf.read().strip())
             pf.close()
         except IOError:
             pid = None
 
         if not pid:
             pid = int(pf.read().strip())
             pf.close()
         except IOError:
             pid = None
 
         if not pid:
-            message = 'pidfile %s does not exist. Is the Daemon running?\n'
-            sys.stderr.write(message % self.pidfile)
+            message = 'pidfile {0.pidfile} does not exist. Is the Daemon running?\n'
+            sys.stderr.write(message.format(self))
             return  # not an error in a restart
 
         # Try killing the daemon process
         try:
             os.kill(pid, SIGTERM)
             time.sleep(0.1)
             return  # not an error in a restart
 
         # Try killing the daemon process
         try:
             os.kill(pid, SIGTERM)
             time.sleep(0.1)
-        except OSError, err:
+        except OSError as err:
             if err.errno == 3:
                 if os.path.exists(self.pidfile):
             if err.errno == 3:
                 if os.path.exists(self.pidfile):
-                    message = "Daemon's not running? removing pid file %s.\n"
-                    sys.stderr.write(message % self.pidfile)
+                    message = "Daemon's not running? removing pid file {0.pidfile}.\n"
+                    sys.stderr.write(message.format(self))
                     os.remove(self.pidfile)
             else:
                 sys.stderr.write(err.strerror)
                     os.remove(self.pidfile)
             else:
                 sys.stderr.write(err.strerror)