root / pykota / trunk / bin / pkprinters @ 2237

Revision 2216, 11.1 kB (checked in by jerome, 20 years ago)

Now exits with no traceback in case of Ctrl+C

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