root / pykota / trunk / bin / pykosd @ 2512

Revision 2512, 7.5 kB (checked in by jerome, 19 years ago)

Ensure that human made errors (like incorrect command line options)
don't produce a traceback anymore. No need to frighten users with
such complete tracebacks and email reporting each time they mistype
some command.
Makes pykosd check more carefully the values of its command line options.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3
4# PyKota Print Quota Editor
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003, 2004, 2005 Jerome Alet <alet@librelogiciel.com>
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 2 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program; if not, write to the Free Software
21# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22#
23# $Id$
24#
25#
26
27import sys
28import os
29import pwd
30import time
31
32try :
33    import pyosd
34except ImportError :   
35    sys.stderr.write("Sorry ! You need both xosd and the Python OSD library (pyosd) for this software to work.\n")
36    sys.exit(-1)
37
38from pykota.tool import PyKotaTool, PyKotaToolError, PyKotaCommandLineError, crashed, N_
39
40__doc__ = N_("""pykosd v%(__version__)s (c) %(__years__)s %(__author__)s
41
42An OSD quota monitor for PyKota.
43
44command line usage :
45
46  pykosd [options]
47
48options :
49
50  -v | --version       Prints pykosd's version number then exits.
51  -h | --help          Prints this message then exits.
52 
53  -c | --color #rrggbb Sets the color to use for display as an hexadecimal
54                       triplet, for example #FF0000 is 100%% red.
55                       Defaults to 100%% green (#00FF00).
56                       
57  -d | --duration d    Sets the duration of the display in seconds.
58                       Defaults to 3 seconds.
59                       
60  -f | --font f        Sets the font to use for display.                     
61                       Defaults to the Python OSD library's default.
62 
63  -l | --loop n        Sets the number of times the info will be displayed.
64                       Defaults to 0, which means loop forever.
65                       
66  -s | --sleep s       Sets the sleeping duration between two displays
67                       in seconds. Defaults to 180 seconds (3 minutes).
68                       
69 
70examples :                             
71
72  $ pykosd -s 60 --loop 5
73 
74  Will launch pykosd. Display will be refreshed every 60 seconds,
75  and will last for 3 seconds (the default) each time. After five
76  iterations, the program will exit.
77""")
78
79
80class PyKOSD(PyKotaTool) :
81    def main(self, args, options) :
82        """Main function starts here."""
83        try :   
84            duration = int(options["duration"])
85            if duration <= 0 :
86                raise ValueError 
87        except :   
88            raise PyKotaCommandLineError, _("Invalid duration option %s") % str(options["duration"])
89           
90        try :   
91            loop = int(options["loop"])
92            if loop < 0 :
93                raise ValueError
94        except :   
95            raise PyKotaCommandLineError, _("Invalid loop option %s") % str(options["loop"])
96           
97        try :   
98            sleep = float(options["sleep"])
99            if sleep <= 0 :
100                raise ValueError
101        except :   
102            raise PyKotaCommandLineError, _("Invalid sleep option %s") % str(options["sleep"])
103           
104        color = options["color"]   
105        if not color.startswith("#") :
106            color = "#%s" % color
107        if len(color) != 7 :   
108            raise PyKotaCommandLineError, _("Invalid color option %s") % str(color)
109        savecolor = color
110       
111        uname = pwd.getpwuid(os.getuid())[0]
112        while 1 :
113            color = savecolor
114            user = cmd.storage.getUserFromBackend(uname)        # don't use cache
115            if not user.Exists :
116                raise PyKotaCommandLineError, _("User %s doesn't exist in PyKota's database") % uname
117            if user.LimitBy == "quota" :   
118                printers = cmd.storage.getMatchingPrinters("*")
119                upquotas = [ cmd.storage.getUserPQuotaFromBackend(user, p) for p in printers ] # don't use cache
120                nblines = len(upquotas)
121                display = pyosd.osd(font=options["font"], colour=color, timeout=duration, shadow=2, lines=nblines)
122                for line in range(nblines) :
123                    upq = upquotas[line]
124                    if upq.HardLimit is None :
125                        if upq.SoftLimit is None :
126                            percent = "%s" % upq.PageCounter
127                        else :       
128                            percent = "%s%%" % min((upq.PageCounter * 100) / upq.SoftLimit, 100)
129                    else :       
130                        percent = "%s%%" % min((upq.PageCounter * 100) / upq.HardLimit, 100)
131                    display.display(_("Pages used on %s : %s") % (upq.Printer.Name, percent), type=pyosd.TYPE_STRING, line=line)
132            else :
133                if user.AccountBalance <= 0 :
134                    color = "#FF0000"
135                display = pyosd.osd(font=options["font"], colour=color, timeout=duration, shadow=2)
136                display.display(_("PyKota Units left : %.2f") % user.AccountBalance, type=pyosd.TYPE_STRING)
137               
138            time.sleep(duration + 1)
139            if loop :
140                loop -= 1
141                if not loop :
142                    break
143            time.sleep(sleep)       
144           
145        return 0   
146       
147if __name__ == "__main__" :
148    retcode = -1
149    try :
150        defaults = { \
151                     "color" : "#00FF00", \
152                     "duration" : "3", \
153                     "font" : pyosd.default_font, \
154                     "loop" : "0", \
155                     "sleep" : "180", \
156                   }
157        short_options = "hvc:d:f:l:s:"
158        long_options = ["help", "version", "color=", "colour=", "duration=", "font=", "loop=", "sleep="]
159       
160        cmd = PyKOSD(doc=__doc__)
161        cmd.deferredInit()
162       
163        # parse and checks the command line
164        (options, args) = cmd.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1)
165       
166        # sets long options
167        options["help"] = options["h"] or options["help"]
168        options["version"] = options["v"] or options["version"]
169        options["color"] = options["c"] or options["color"] or options["colour"] or defaults["color"]
170        options["duration"] = options["d"] or options["duration"] or defaults["duration"]
171        options["font"] = options["f"] or options["font"] or defaults["font"]
172        options["loop"] = options["l"] or options["loop"] or defaults["loop"]
173        options["sleep"] = options["s"] or options["sleep"] or defaults["sleep"]
174       
175        if options["help"] :
176            cmd.display_usage_and_quit()
177        elif options["version"] :
178            cmd.display_version_and_quit()
179        else :   
180            retcode = cmd.main(args, options)
181    except KeyboardInterrupt :
182        retcode = 0
183    except KeyboardInterrupt :       
184        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
185    except PyKotaCommandLineError, msg :   
186        sys.stderr.write("%s : %s\n" % (sys.argv[0], msg))
187    except SystemExit :       
188        pass
189    except :   
190        try :
191            cmd.crashed("pykosd failed")
192        except :   
193            crashed("pykosd failed")
194       
195    try :
196        cmd.storage.close()
197    except :   
198        pass
199       
200    sys.exit(retcode)
Note: See TracBrowser for help on using the browser.