root / pykota / trunk / bin / pkprinters @ 1471

Revision 1453, 11.1 kB (checked in by jalet, 21 years ago)

Added --skipexisting command line option to pkprinters

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