root / pykota / trunk / bin / pkprinters @ 1597

Revision 1584, 12.2 kB (checked in by jalet, 20 years ago)

Better dispatching of error messages

  • 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 Printers Manager
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003-2004 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22#
23# $Id$
24#
25# $Log$
26# Revision 1.13  2004/07/01 19:56:41  jalet
27# Better dispatching of error messages
28#
29# Revision 1.12  2004/07/01 17:45:47  jalet
30# Added code to handle the description field for printers
31#
32# Revision 1.11  2004/06/18 13:34:48  jalet
33# Now all tracebacks include PyKota's version number
34#
35# Revision 1.10  2004/06/07 18:43:40  jalet
36# Fixed over-verbose exits when displaying help or version number
37#
38# Revision 1.9  2004/06/03 21:50:34  jalet
39# Improved error logging.
40# crashrecipient directive added.
41# Now exports the job's size in bytes too.
42#
43# Revision 1.8  2004/05/06 20:30:24  jalet
44# Added --skipexisting command line option to pkprinters
45#
46# Revision 1.7  2004/05/06 12:51:58  jalet
47# Documentation
48#
49# Revision 1.6  2004/05/06 12:37:29  jalet
50# pkpgcounter : comments
51# pkprinters : when --add is used, existing printers are now skipped.
52#
53# Revision 1.5  2004/04/16 16:52:09  jalet
54# Better formatting
55#
56# Revision 1.4  2004/04/16 16:47:57  jalet
57# pkprinters now accept the --list command line option
58#
59# Revision 1.3  2004/02/04 13:24:41  jalet
60# pkprinters can now remove printers from printers groups.
61#
62# Revision 1.2  2004/02/04 12:52:37  jalet
63# pkprinters' help
64#
65# Revision 1.1  2004/02/04 11:16:59  jalet
66# pkprinters command line tool added.
67#
68#
69#
70
71import sys
72
73from pykota import version
74from pykota.tool import PyKotaTool, PyKotaToolError, crashed
75from pykota.config import PyKotaConfigError
76from pykota.storage import PyKotaStorageError
77
78__doc__ = """pkprinters v%s (c) 2003-2004 C@LL - Conseil Internet & Logiciels Libres
79A Printers Manager for PyKota.
80
81command line usage :
82
83  pkprinters [options] printer1 printer2 printer3 ... printerN
84
85options :
86
87  -v | --version       Prints pkprinters's version number then exits.
88  -h | --help          Prints this message then exits.
89 
90  -a | --add           Adds printers if they don't exist on the Quota
91                       Storage Server. If they exist, they are modified
92                       unless -s|--skipexisting is also used.
93                       
94  -d | --delete        Deletes printers from the quota storage.
95 
96  -D | --description   Adds a textual description to printers.
97                       
98  -c | --charge p[,j]  Sets the price per page and per job to charge.
99                       Job price is optional.
100                       If both are to be set, separate them with a comma.
101                       Floating point and negative values are allowed.
102 
103  -g | --groups pg1[,pg2...] Adds or Remove the printer(s) to the printer
104                       groups pg1, pg2, etc... which must already exist.
105                       A printer group is just like a normal printer,
106                       only that it is usually unknown from the printing
107                       system. Create printer groups exactly the same
108                       way that you create printers, then add other
109                       printers to them with this option.
110                       Accounting is done on a printer and on all
111                       the printer groups it belongs to, quota checking
112                       is done on a printer and on all the printer groups
113                       it belongs to.
114                       If the --remove option below is not used, the
115                       default action is to add printers to the specified
116                       printer groups.
117                       
118  -l | --list          List informations about the printer(s) and the
119                       printers groups it is a member of.
120                       
121  -r | --remove        In combination with the --groups option above,                       
122                       remove printers from the specified printers groups.
123                       
124  -s | --skipexisting  In combination with the --add option above, tells
125                       pkprinters to not modify existing printers.
126 
127  printer1 through printerN can contain wildcards if the --add option
128  is not set.
129 
130examples :                             
131
132  $ pkprinters --add -D "HP Printer" --charge 0.05,0.1 hp2100 hp2200 hp8000
133 
134  Will create three printers named hp2100, hp2200 and hp8000.
135  Their price per page will be set at 0.05 unit, and their price
136  per job will be set at 0.1 unit. Units are in your own currency,
137  or whatever you want them to mean.
138  All of their descriptions will be set to the string "HP Printer".
139  If any of these printers already exists, it will also be modified
140  unless the -s|--skipexisting command line option is also used.
141           
142  $ pkprinters --delete "*"
143 
144  This will completely delete all printers and associated quota information,
145  as well as their job history. USE WITH CARE !
146 
147  $ pkprinters --groups Laser,HP "hp*"
148 
149  This will put all printers which name matches "hp*" into printers groups
150  Laser and HP, which MUST already exist.
151 
152  $ pkprinters --groups LexMark --remove hp2200
153 
154  This will remove the hp2200 printer from the LexMark printer group.
155 
156This program is free software; you can redistribute it and/or modify
157it under the terms of the GNU General Public License as published by
158the Free Software Foundation; either version 2 of the License, or
159(at your option) any later version.
160
161This program is distributed in the hope that it will be useful,
162but WITHOUT ANY WARRANTY; without even the implied warranty of
163MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
164GNU General Public License for more details.
165
166You should have received a copy of the GNU General Public License
167along with this program; if not, write to the Free Software
168Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
169
170Please e-mail bugs to: %s""" % (version.__version__, version.__author__)
171       
172class PKPrinters(PyKotaTool) :       
173    """A class for edpykota."""
174    def main(self, names, options) :
175        """Manage printers."""
176        if options["list"] and not names :
177            names = ["*"]
178           
179        if options["groups"] :       
180            printersgroups = self.storage.getMatchingPrinters(options["groups"])
181            if not printersgroups :
182                raise PyKotaToolError, _("There's no printer matching %s") % " ".join(options["groups"].split(','))
183           
184        if options["charge"] :
185            try :
186                charges = [float(part) for part in options["charge"].split(',', 1)]
187            except ValueError :   
188                raise PyKotaToolError, _("Invalid charge amount value %s") % options["charge"]
189            else :   
190                if len(charges) > 2 :
191                    charges = charges[:2]
192                if len(charges) != 2 :
193                    charges = [charges[0], None]
194                (perpage, perjob) = charges
195               
196        if options["add"] :   
197            printers = []
198            for pname in names :
199                printer = self.storage.getPrinter(pname)
200                if printer.Exists :
201                    if options["skipexisting"] :
202                        self.printInfo(_("Printer %s already exists, skipping.") % printer.Name)
203                    else :   
204                        self.printInfo(_("Printer %s already exists, will be modified.") % printer.Name)
205                        printers.append(printer)
206                else :
207                    if self.isValidName(pname) :
208                        printer = self.storage.addPrinter(pname)
209                        if not printer.Exists :
210                            raise PyKotaToolError, _("Impossible to add printer %s") % pname
211                        else :   
212                            printers.append(printer)
213                    else :   
214                        raise PyKotaToolError, _("Invalid printer name %s") % pname
215        else :       
216            printers = self.storage.getMatchingPrinters(",".join(names))
217            if not printers :
218                raise PyKotaToolError, _("There's no printer matching %s") % " ".join(names)
219                   
220        for printer in printers :       
221            if options["delete"] :
222                printer.delete()
223            elif options["list"] :   
224                parents = ", ".join([p.Name for p in self.storage.getParentPrinters(printer)])
225                if parents : 
226                    parents = "%s %s" % (_("in"), parents)
227                print "%s [%s] (%s + #*%s) %s" % \
228                      (printer.Name, printer.Description, printer.PricePerJob, \
229                       printer.PricePerPage, parents)
230            else :   
231                if options["charge"] :
232                    printer.setPrices(perpage, perjob)   
233                if options["description"] is not None :
234                    printer.setDescription(options["description"].strip())
235                if options["groups"] :   
236                    for pgroup in printersgroups :
237                        if options["remove"] :
238                            pgroup.delPrinterFromGroup(printer)
239                        else :
240                            pgroup.addPrinterToGroup(printer)   
241                     
242if __name__ == "__main__" : 
243    retcode = 0
244    try :
245        short_options = "hvac:D:dg:lrs"
246        long_options = ["help", "version", "add", "charge=", "description=", "delete", "groups=", "list", "remove", "skipexisting"]
247       
248        # Initializes the command line tool
249        manager = PKPrinters(doc=__doc__)
250       
251        # parse and checks the command line
252        (options, args) = manager.parseCommandline(sys.argv[1:], short_options, long_options)
253       
254        # sets long options
255        options["help"] = options["h"] or options["help"]
256        options["version"] = options["v"] or options["version"]
257        options["add"] = options["a"] or options["add"]
258        options["charge"] = options["c"] or options["charge"]
259        options["description"] = options["D"] or options["description"]
260        options["delete"] = options["d"] or options["delete"] 
261        options["groups"] = options["g"] or options["groups"]
262        options["list"] = options["l"] or options["list"]
263        options["remove"] = options["r"] or options["remove"]
264        options["skipexisting"] = options["s"] or options["skipexisting"]
265       
266        if options["help"] :
267            manager.display_usage_and_quit()
268        elif options["version"] :
269            manager.display_version_and_quit()
270        elif (options["delete"] and (options["add"] or options["groups"] or options["charge"] or options["remove"] or options["description"])) \
271           or (options["skipexisting"] and not options["add"]) \
272           or (options["list"] and (options["add"] or options["delete"] or options["groups"] or options["charge"] or options["remove"] or options["description"])) :
273            raise PyKotaToolError, _("incompatible options, see help.")
274        elif options["remove"] and not options["groups"] :   
275            raise PyKotaToolError, _("You have to pass printer groups names on the command line")
276        elif (not args) and (not options["list"]) :   
277            raise PyKotaToolError, _("You have to pass printer names on the command line")
278        else :
279            retcode = manager.main(args, options)
280    except SystemExit :       
281        pass
282    except :
283        try :
284            manager.crashed("pkprinters failed")
285        except :   
286            crashed("pkprinters failed")
287        retcode = -1
288
289    try :
290        manager.storage.close()
291    except (TypeError, NameError, AttributeError) :   
292        pass
293       
294    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.