root / pykota / trunk / bin / pkprinters @ 1574

Revision 1546, 11.5 kB (checked in by jalet, 20 years ago)

Now all tracebacks include PyKota's version number

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