Changeset 3328

Show
Ignore:
Timestamp:
02/02/08 21:57:51 (16 years ago)
Author:
jerome
Message:

pykosd converted to new style.

Files:
1 modified

Legend:

Unmodified
Added
Removed
  • pykota/trunk/bin/pykosd

    r3295 r3328  
    3535import pykota.appinit 
    3636from pykota.utils import * 
    37  
     37from pykota.commandline import PyKotaOptionParser 
    3838from pykota.errors import PyKotaToolError, PyKotaCommandLineError 
    3939from pykota.tool import PyKotaTool 
    4040 
    41 __doc__ = N_("""pykosd v%(__version__)s (c) %(__years__)s %(__author__)s 
    42  
    43 An OSD quota monitor for PyKota. 
    44  
    45 command line usage : 
    46  
    47   pykosd [options] 
    48  
    49 options : 
    50  
    51   -v | --version       Prints pykosd's version number then exits. 
    52   -h | --help          Prints this message then exits. 
    53    
    54   -c | --color #rrggbb Sets the color to use for display as an hexadecimal 
    55                        triplet, for example #FF0000 is 100%% red. 
    56                        Defaults to 100%% green (#00FF00). 
    57                         
    58   -d | --duration d    Sets the duration of the display in seconds.  
    59                        Defaults to 3 seconds. 
    60                         
    61   -f | --font f        Sets the font to use for display.                       
    62                        Defaults to the Python OSD library's default. 
    63    
    64   -l | --loop n        Sets the number of times the info will be displayed. 
    65                        Defaults to 0, which means loop forever. 
    66                         
    67   -s | --sleep s       Sets the sleeping duration between two displays  
    68                        in seconds. Defaults to 180 seconds (3 minutes). 
    69                         
    70    
    71 examples :                               
    72  
    73   $ pykosd -s 60 --loop 5 
    74    
    75   Will launch pykosd. Display will be refreshed every 60 seconds, 
    76   and will last for 3 seconds (the default) each time. After five 
    77   iterations, the program will exit. 
    78 """) 
    79  
     41"""An On Screen Display (OSD) monitor for PyKota's end users.""" 
    8042 
    8143class PyKOSD(PyKotaTool) : 
     
    8345    def main(self, args, options) : 
    8446        """Main function starts here.""" 
    85         try :     
    86             duration = int(options["duration"]) 
    87             if duration <= 0 : 
    88                 raise ValueError  
    89         except :     
    90             raise PyKotaCommandLineError, _("Invalid duration option %s") % str(options["duration"]) 
    91              
    92         try :     
    93             loop = int(options["loop"]) 
    94             if loop < 0 : 
    95                 raise ValueError 
    96         except :     
    97             raise PyKotaCommandLineError, _("Invalid loop option %s") % str(options["loop"]) 
    98              
    99         try :     
    100             sleep = float(options["sleep"]) 
    101             if sleep <= 0 : 
    102                 raise ValueError 
    103         except :     
    104             raise PyKotaCommandLineError, _("Invalid sleep option %s") % str(options["sleep"]) 
    105              
    106         color = options["color"]     
    107         if not color.startswith("#") : 
    108             color = "#%s" % color 
    109         if len(color) != 7 :     
    110             raise PyKotaCommandLineError, _("Invalid color option %s") % str(color) 
    111         savecolor = color 
    112          
    113         uname = pwd.getpwuid(os.getuid())[0] 
    114         while 1 : 
     47        savecolor = options.color 
     48        loop = options.loop 
     49        username = pwd.getpwuid(os.getuid())[0] 
     50        while True : 
    11551            color = savecolor 
    116             user = self.storage.getUserFromBackend(uname)        # don't use cache 
     52            user = self.storage.getUserFromBackend(username) # don't use cache 
    11753            if not user.Exists : 
    118                 raise PyKotaCommandLineError, _("User %s doesn't exist in PyKota's database") % uname 
     54                raise PyKotaCommandLineError, _("You %(username)s don't have a PyKota printing account. Please contact your administrator.") % locals() 
    11955            if user.LimitBy == "quota" :     
    12056                printers = self.storage.getMatchingPrinters("*") 
    12157                upquotas = [ self.storage.getUserPQuotaFromBackend(user, p) for p in printers ] # don't use cache 
    12258                nblines = len(upquotas) 
    123                 display = pyosd.osd(font=options["font"], colour=color, timeout=duration, shadow=2, lines=nblines) 
     59                display = pyosd.osd(font=options.font,  
     60                                    colour=color,  
     61                                    timeout=options.duration,  
     62                                    shadow=2,  
     63                                    lines=nblines) 
    12464                for line in range(nblines) : 
    12565                    upq = upquotas[line] 
    12666                    if upq.HardLimit is None : 
    12767                        if upq.SoftLimit is None : 
    128                             percent = "%s" % upq.PageCounter 
     68                            percent = "%i" % upq.PageCounter 
    12969                        else :         
    130                             percent = "%s%%" % min((upq.PageCounter * 100) / upq.SoftLimit, 100) 
     70                            percent = "%i%%" % min((upq.PageCounter * 100) / upq.SoftLimit, 100) 
    13171                    else :         
    132                         percent = "%s%%" % min((upq.PageCounter * 100) / upq.HardLimit, 100) 
    133                     display.display(_("Pages used on %s : %s") % (upq.Printer.Name, percent), type=pyosd.TYPE_STRING, line=line) 
     72                        percent = "%i%%" % min((upq.PageCounter * 100) / upq.HardLimit, 100) 
     73                    printername = upq.Printer.Name     
     74                    msg = _("Pages used on %(printername)s : %(percent)s") % locals() 
     75                    display.display(msg.encode(self.charset, "replace"),  
     76                                    type=pyosd.TYPE_STRING,  
     77                                    line=line) 
    13478            elif user.LimitBy == "balance" : 
    13579                if user.AccountBalance <= self.config.getBalanceZero() : 
    13680                    color = "#FF0000" 
    137                 display = pyosd.osd(font=options["font"], colour=color, timeout=duration, shadow=2) 
    138                 display.display(_("PyKota Units left : %.2f") % user.AccountBalance, type=pyosd.TYPE_STRING) 
     81                display = pyosd.osd(font=options.font,  
     82                                    colour=color,  
     83                                    timeout=options.duration,  
     84                                    shadow=2) 
     85                balance = user.AccountBalance                     
     86                msg = _("PyKota Units left : %(balance).2f") % locals() 
     87                display.display(msg.encode(self.charset, "replace"),  
     88                                type=pyosd.TYPE_STRING) 
    13989            elif user.LimitBy == "noprint" :     
    140                 display = pyosd.osd(font=options["font"], colour="#FF0000", timeout=duration, shadow=2) 
    141                 display.display(_("Printing denied."), type=pyosd.TYPE_STRING) 
     90                display = pyosd.osd(font=options.font,  
     91                                    colour="#FF0000",  
     92                                    timeout=options.duration,  
     93                                    shadow=2) 
     94                msg = _("Printing denied.") 
     95                display.display(msg.encode(self.charset, "replace"),  
     96                                type=pyosd.TYPE_STRING) 
    14297            elif user.LimitBy == "noquota" :     
    143                 display = pyosd.osd(font=options["font"], colour=savecolor, timeout=duration, shadow=2) 
    144                 display.display(_("Printing not limited."), type=pyosd.TYPE_STRING) 
     98                display = pyosd.osd(font=options.font,  
     99                                    colour=savecolor,  
     100                                    timeout=options.duration,  
     101                                    shadow=2) 
     102                msg = _("Printing not limited.") 
     103                display.display(msg.encode(self.charset, "replace"),  
     104                                type=pyosd.TYPE_STRING) 
    145105            elif user.LimitBy == "nochange" :     
    146                 display = pyosd.osd(font=options["font"], colour=savecolor, timeout=duration, shadow=2) 
    147                 display.display(_("Printing not limited, no accounting."), type=pyosd.TYPE_STRING) 
     106                display = pyosd.osd(font=options.font,  
     107                                    colour=savecolor,  
     108                                    timeout=options.duration,  
     109                                    shadow=2) 
     110                msg = _("Printing not limited, no accounting.") 
     111                display.display(msg.encode(self.charset, "replace"),  
     112                                type=pyosd.TYPE_STRING) 
    148113            else :     
    149                 raise PyKotaToolError, "Incorrect limitation factor %s for user %s" % (repr(user.LimitBy), user.Name) 
     114                limitby = repr(user.LimitBy) 
     115                raise PyKotaToolError, "Incorrect limitation factor %(limitby)s for user %(username)s" % locals() 
    150116                 
    151             time.sleep(duration + 1) 
     117            time.sleep(options.duration + 1) 
    152118            if loop : 
    153119                loop -= 1 
    154120                if not loop : 
    155121                    break 
    156             time.sleep(sleep)         
     122            time.sleep(options.sleep)         
    157123             
    158124        return 0     
    159125         
    160126if __name__ == "__main__" : 
    161     retcode = -1 
    162     try : 
    163         defaults = { \ 
    164                      "color" : "#00FF00", \ 
    165                      "duration" : "3", \ 
    166                      "font" : pyosd.default_font, \ 
    167                      "loop" : "0", \ 
    168                      "sleep" : "180", \ 
    169                    } 
    170         short_options = "hvc:d:f:l:s:" 
    171         long_options = ["help", "version", "color=", "colour=", "duration=", "font=", "loop=", "sleep="] 
    172          
    173         cmd = PyKOSD(doc=__doc__) 
    174         cmd.deferredInit() 
    175          
    176         # parse and checks the command line 
    177         (options, args) = cmd.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1) 
    178          
    179         # sets long options 
    180         options["help"] = options["h"] or options["help"] 
    181         options["version"] = options["v"] or options["version"] 
    182         options["color"] = options["c"] or options["color"] or options["colour"] or defaults["color"] 
    183         options["duration"] = options["d"] or options["duration"] or defaults["duration"] 
    184         options["font"] = options["f"] or options["font"] or defaults["font"] 
    185         options["loop"] = options["l"] or options["loop"] or defaults["loop"] 
    186         options["sleep"] = options["s"] or options["sleep"] or defaults["sleep"] 
    187          
    188         if options["help"] : 
    189             cmd.display_usage_and_quit() 
    190         elif options["version"] : 
    191             cmd.display_version_and_quit() 
     127    def checkandset_positiveint(option, opt, value, parser) :     
     128        """Checks and sets positive integer values.""" 
     129        if value < 0 : 
     130            loginvalidparam(opt, value, option.default) 
     131            setattr(parser.values, option.dest, option.default) 
    192132        else :     
    193             retcode = cmd.main(args, options) 
    194     except KeyboardInterrupt : 
    195         retcode = 0 
    196     except KeyboardInterrupt :         
    197         logerr("\nInterrupted with Ctrl+C !\n") 
    198         retcode = -3 
    199     except PyKotaCommandLineError, msg :     
    200         logerr("%s : %s\n" % (sys.argv[0], msg)) 
    201         retcode = -2 
    202     except SystemExit :         
    203         pass 
    204     except :     
    205         try : 
    206             cmd.crashed("pykosd failed") 
    207         except :     
    208             crashed("pykosd failed") 
    209          
    210     try : 
    211         cmd.storage.close() 
    212     except :     
    213         pass 
    214          
    215     sys.exit(retcode) 
     133            setattr(parser.values, option.dest, value) 
     134             
     135    def checkandset_color(option, opt, value, parser) :     
     136        """Checks and sets the color value.""" 
     137        if not value.startswith("#") : 
     138            value = "#%s" % value 
     139        try :     
     140            int(value[1:], 16) 
     141        except (ValueError, TypeError) :     
     142            error = True 
     143        else :     
     144            error = False 
     145        if (len(value) != 7) or error : 
     146            loginvalidparam(opt, value, option.default) 
     147            setattr(parser.values, option.dest, option.default) 
     148        else :     
     149            setattr(parser.values, option.dest, value) 
     150             
     151    parser = PyKotaOptionParser(description=_("An On Screen Display (OSD) monitor for PyKota's end users.")) 
     152    parser.add_option("-c", "--color", "--colour", 
     153                            action="callback", 
     154                            callback=checkandset_color, 
     155                            dest="color", 
     156                            default="#00FF00", 
     157                            help=_("Set the color that will be used for display, as an hexadecimal triplet. For example #FF0000 is 100% red. The default is 100% green (%default).")) 
     158    parser.add_option("-d", "--duration", 
     159                            type="int", 
     160                            action="callback", 
     161                            callback=checkandset_positiveint, 
     162                            dest="duration", 
     163                            default=3, 
     164                            help=_("Set the time in seconds during which the message will be displayed. Defaults to %default seconds.")) 
     165    parser.add_option("-f", "--font", 
     166                            dest="font", 
     167                            default=pyosd.default_font, 
     168                            help=_("Set the font to use. Defaults to %default.")) 
     169    parser.add_option("-l", "--loop", 
     170                            type="int", 
     171                            action="callback", 
     172                            callback=checkandset_positiveint, 
     173                            dest="loop", 
     174                            default=0, 
     175                            help=_("Set the number of times the info will be displayed. Defaults to %default, which means loop forever.")) 
     176    parser.add_option("-s", "--sleep", 
     177                            type="int", 
     178                            action="callback", 
     179                            callback=checkandset_positiveint, 
     180                            dest="sleep", 
     181                            default=180, 
     182                            help=_("Set the sleeping time in seconds between two refreshes. Defaults to %default seconds.")) 
     183                             
     184    parser.add_example('-s 60 --loop 5', 
     185                       _("This would tell pykosd to display the current user's status for 3 seconds (the default) every 60 seconds, and exit after 5 iterations.")) 
     186                        
     187    run(parser, PyKOSD)