Show
Ignore:
Timestamp:
03/29/08 10:10:29 (16 years ago)
Author:
jerome
Message:

Added support for the -u|--user command line option : PyKota administrators
can now generate a print quote for any other user. This option is ignored
when the command is launched by a mere mortal.
pykotme now support new style option parsing.

Files:
1 modified

Legend:

Unmodified
Added
Removed
  • pykota/trunk/bin/pykotme

    r3295 r3358  
    2222# 
    2323 
     24"""A print quote generator for PyKota""" 
     25 
    2426import sys 
    2527import os 
     
    2729 
    2830import pykota.appinit 
    29 from pykota.utils import * 
    30  
     31from pykota.utils import run 
     32from pykota.commandline import PyKotaOptionParser 
    3133from pykota.errors import PyKotaCommandLineError 
    3234from pykota.tool import PyKotaTool 
    3335from pykota.accounter import openAccounter 
    3436     
    35  
    36 __doc__ = N_("""pykotme v%(__version__)s (c) %(__years__)s %(__author__)s 
    37  
    38 Gives print quotes to users. 
    39  
    40 command line usage : 
    41  
    42   pykotme  [options]  [files] 
    43  
    44 options : 
    45  
    46   -v | --version       Prints pykotme's version number then exits. 
    47   -h | --help          Prints this message then exits. 
    48    
    49   -P | --printer p     Gives a quote for this printer only. Actually p can 
    50                        use wildcards characters to select only 
    51                        some printers. The default value is *, meaning 
    52                        all printers. 
    53                        You can specify several names or wildcards,  
    54                        by separating them with commas. 
    55    
    56 examples :                               
    57  
    58   $ pykotme --printer apple file1.ps file2.ps 
    59    
    60   This will give a print quote to the current user. The quote will show 
    61   the price and size of a job consisting in file1.ps and file2.ps  
    62   which would be sent to the apple printer. 
    63    
    64   $ pykotme --printer apple,hplaser <file1.ps 
    65    
    66   This will give a print quote to the current user. The quote will show 
    67   the price and size of a job consisting in file1.ps as read from 
    68   standard input, which would be sent to the apple or hplaser 
    69   printer. 
    70  
    71   $ pykotme  
    72    
    73   This will give a quote for a job consisting of what is on standard  
    74   input. The quote will list the job size, and the price the job 
    75   would cost on each printer. 
    76 """) 
    77          
    78          
    7937class PyKotMe(PyKotaTool) :         
    8038    """A class for pykotme.""" 
     
    8240        """Gives print quotes.""" 
    8341        if (not sys.stdin.isatty()) and ("-" not in files) : 
     42            # TODO : create a named temporary file for standard input 
     43            # TODO : because if there are several printers on the command 
     44            # TODO : line and they have different preaccounter directives, 
     45            # TODO : the standard input will already be consumed when looping 
     46            # TODO : over the second printer below. 
    8447            files.append("-") 
    8548             
    86         printers = self.storage.getMatchingPrinters(options["printer"]) 
     49        printers = self.storage.getMatchingPrinters(options.printer) 
    8750        if not printers : 
    88             raise PyKotaCommandLineError, _("There's no printer matching %s") % options["printer"] 
     51            raise PyKotaCommandLineError, _("There's no printer matching %s") % options.printer 
    8952             
    9053        username = pwd.getpwuid(os.getuid())[0] 
     54        if options.user : 
     55            if not self.config.isAdmin : 
     56                self.printInfo(_("The --user command line option will be ignored because you are not a PyKota Administrator."), "warn") 
     57            else :     
     58                username = options.user 
     59             
    9160        user = self.storage.getUser(username) 
    92         if user.Exists and user.LimitBy and (user.LimitBy.lower() == "balance"): 
    93             print _("Your account balance : %.2f") % (user.AccountBalance or 0.0) 
     61        if not user.Exists : 
     62            self.printInfo(_("There's no user matching '%(username)s'.") \ 
     63                                              % locals(), 
     64                           "error")                    
     65        else :                    
     66            if user.LimitBy and (user.LimitBy.lower() == "balance"): 
     67                self.display("%s\n" % (_("Your account balance : %.2f") % (user.AccountBalance or 0.0))) 
    9468             
    95         if user.Exists : 
    9669            sizeprinted = False 
    9770            done = {} 
    9871            for printer in printers : 
    9972                # Now fake some values. TODO : improve API to not need this anymore     
     73                printername = printer.Name 
    10074                self.PrinterName = printer.Name 
    10175                self.JobSizeBytes = 1 
     
    11488                (totalsize, inkusage) = done[key]     
    11589                if not sizeprinted :     
    116                     print _("Job size : %i pages") % totalsize     
     90                    self.display("%s\n" % (_("Job size : %i pages") % totalsize)) 
    11791                    sizeprinted = True 
    11892                userpquota = self.storage.getUserPQuota(user, printer) 
    11993                if userpquota.Exists : 
    12094                    if printer.MaxJobSize and (totalsize > printer.MaxJobSize) : 
    121                         print _("You are not allowed to print so many pages on printer %s at this time.") % printer.Name 
     95                        self.display("%s\n" % (_("User %(username)s is not allowed to print so many pages on printer %(printername)s at this time.") % locals())) 
    12296                    else :     
    12397                        cost = userpquota.computeJobPrice(totalsize, inkusage) 
     
    126100                            msg = "%s (%s)" % (msg, _("won't be charged, printer is in passthrough mode")) 
    127101                        elif user.LimitBy == "nochange" :     
    128                             msg = "%s (%s)" % (msg, _("won't be charged, your account is immutable")) 
    129                         print msg     
     102                            msg = "%s (%s)" % (msg, _("won't be charged, account is immutable")) 
     103                        self.display("%s\n" % msg) 
    130104            if user.LimitBy == "noprint" : 
    131                 print _("Your account settings forbid you to print at this time.") 
     105                self.display("%s\n" % (_("User %(username)s is forbidden to print at this time.") % locals())) 
    132106             
    133107if __name__ == "__main__" :  
    134     retcode = 0 
    135     try : 
    136         defaults = { \ 
    137                      "printer" : "*", \ 
    138                    } 
    139         short_options = "vhP:" 
    140         long_options = ["help", "version", "printer="] 
    141          
    142         # Initializes the command line tool 
    143         sender = PyKotMe(doc=__doc__) 
    144         sender.deferredInit() 
    145          
    146         # parse and checks the command line 
    147         (options, args) = sender.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1) 
    148          
    149         # sets long options 
    150         options["help"] = options["h"] or options["help"] 
    151         options["version"] = options["v"] or options["version"] 
    152         options["printer"] = options["P"] or options["printer"] or defaults["printer"] 
    153          
    154         if options["help"] : 
    155             sender.display_usage_and_quit() 
    156         elif options["version"] : 
    157             sender.display_version_and_quit() 
    158         else : 
    159             retcode = sender.main(args, options) 
    160     except KeyboardInterrupt :         
    161         logerr("\nInterrupted with Ctrl+C !\n") 
    162         retcode = -3 
    163     except PyKotaCommandLineError, msg :     
    164         logerr("%s : %s\n" % (sys.argv[0], msg)) 
    165         retcode = -2 
    166     except SystemExit :         
    167         pass 
    168     except : 
    169         try : 
    170             sender.crashed("pykotme failed") 
    171         except :     
    172             crashed("pykotme failed") 
    173         retcode = -1 
     108    parser = PyKotaOptionParser(description=_("Generates print quotes for end users."), 
     109                                usage="pykotme [options] [files]") 
     110    parser.add_option("-P", "--printer", 
     111                            dest="printer", 
     112                            default="*", 
     113                            help=_("Acts on this printer only. You can specify several printer names by separating them with commas. The default value is '%default', which means all printers.")) 
     114    parser.add_option("-u", "--user", 
     115                            dest="user", 
     116                            help=_("Acts on this user only. Only one username can be specified this way. The default value is the name of the user who launched this command. This option is ignored when the command is not launched by a PyKota Administrator.")) 
    174117 
    175     try : 
    176         sender.storage.close() 
    177     except (TypeError, NameError, AttributeError) :     
    178         pass 
    179          
    180     sys.exit(retcode)     
     118    parser.add_example("--printer apple file1.ps <file2.pclxl",                             
     119                       _("This would show the number of pages needed to print these two files, as well as the cost of printing them to the 'apple' printer.")) 
     120    parser.add_example("--user john", 
     121                       _("This would show the number of pages needed to print the content of the standard input, and the cost of printing this on all printers for user 'john'.")) 
     122    run(parser, PyKotMe)