root / pykota / trunk / bin / pykotme @ 1188

Revision 1156, 7.3 kB (checked in by jalet, 21 years ago)

Multiple printer names or wildcards can be passed on the command line
separated with commas.
Beta phase.

  • 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 Print Quota Quote sender
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003 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.5  2003/10/09 21:25:25  jalet
27# Multiple printer names or wildcards can be passed on the command line
28# separated with commas.
29# Beta phase.
30#
31# Revision 1.4  2003/10/07 09:07:27  jalet
32# Character encoding added to please latest version of Python
33#
34# Revision 1.3  2003/07/29 20:55:17  jalet
35# 1.14 is out !
36#
37# Revision 1.2  2003/07/25 10:41:29  jalet
38# Better documentation.
39# pykotme now displays the current user's account balance.
40# Some test changed in ldap module.
41#
42# Revision 1.1  2003/07/03 09:44:01  jalet
43# Now includes the pykotme utility
44#
45#
46#
47
48import sys
49import os
50import pwd
51
52from pykota import version
53from pykota.tool import PyKotaTool, PyKotaToolError
54from pykota.config import PyKotaConfigError
55from pykota.storage import PyKotaStorageError
56
57__doc__ = """pykotme v%s (C) 2003 C@LL - Conseil Internet & Logiciels Libres
58
59Gives print quotes to users.
60
61command line usage :
62
63  pykotme  [options]  [files]
64
65options :
66
67  -v | --version       Prints pykotme's version number then exits.
68  -h | --help          Prints this message then exits.
69 
70  -P | --printer p     Gives a quote for this printer only. Actually p can
71                       use wildcards characters to select only
72                       some printers. The default value is *, meaning
73                       all printers.
74                       You can specify several names or wildcards,
75                       by separating them with commas.
76 
77examples :                             
78
79  $ pykotme --printer apple file1.ps file2.ps
80 
81  This will give a print quote to the current user. The quote will show
82  the price and size of a job consisting in file1.ps and file2.ps
83  which would be sent to the apple printer.
84 
85  $ pykotme --printer apple,hplaser <file1.ps
86 
87  This will give a print quote to the current user. The quote will show
88  the price and size of a job consisting in file1.ps as read from
89  standard input, which would be sent to the apple or hplaser
90  printer.
91
92  $ pykotme
93 
94  This will give a quote for a job consisting of what is on standard
95  input. The quote will list the job size, and the price the job
96  would cost on each printer.
97
98
99This program is free software; you can redistribute it and/or modify
100it under the terms of the GNU General Public License as published by
101the Free Software Foundation; either version 2 of the License, or
102(at your option) any later version.
103
104This program is distributed in the hope that it will be useful,
105but WITHOUT ANY WARRANTY; without even the implied warranty of
106MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
107GNU General Public License for more details.
108
109You should have received a copy of the GNU General Public License
110along with this program; if not, write to the Free Software
111Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
112
113Please e-mail bugs to: %s""" % (version.__version__, version.__author__)
114       
115class PyKotMe(PyKotaTool) :       
116    """A class for pykotme."""
117    def main(self, files, options) :
118        """Gives print quotes."""
119        if not files :
120            files = [ sys.stdin ]
121           
122        nbpages = 0   
123        for filename in files :
124            if filename is sys.stdin :
125                stream = filename
126            else :
127                if filename == "-" :
128                    stream = sys.stdin
129                else :   
130                    try :
131                        stream = open(filename, "rb")
132                    except IOError, msg :   
133                        sys.stderr.write("%s\n" % msg)
134                        continue
135            nb = self.getNbPages(stream)
136            if nb is None :
137                sys.stderr.write(_("Unable to compute size of %s in number of pages.\n") % filename)
138            else :
139                nbpages += nb
140            if not (filename is sys.stdin) :       
141                stream.close()
142               
143        # get current user
144        uid = os.geteuid()
145        username = pwd.getpwuid(uid)[0]
146        user = self.storage.getUser(username)
147        if user.Exists and user.LimitBy and (user.LimitBy.lower() == "balance"):
148            print _("Your account balance : %.2f") % (user.AccountBalance or 0.0)
149           
150        printers = self.storage.getMatchingPrinters(options["printer"])
151        if not printers :
152            raise PyKotaToolError, _("There's no printer matching %s") % options["printer"]
153           
154        print _("Job size : %i pages") % nbpages   
155        for printer in printers :
156            cost = (nbpages * float(printer.PricePerPage or 0)) + float(printer.PricePerJob or 0)
157            print _("Cost on printer %s : %.2f") % (printer.Name, cost)
158           
159    def getNbPages(self, stream) :       
160        """Tries to compute the file's size in number of pages, the best we can."""
161        nbpages = [] # in case some user wants to put several %%Pages: entries in the file
162        for line in stream.xreadlines() :
163            line = line.strip()
164            if line.startswith("%%Pages: ") :
165                try :
166                    nbpages.append(int(line[9:]))
167                except ValueError :   
168                    pass
169        if nbpages :           
170            return max(nbpages)
171       
172if __name__ == "__main__" : 
173    retcode = 0
174    try :
175        defaults = { \
176                     "printer" : "*", \
177                   }
178        short_options = "vhP:"
179        long_options = ["help", "version", "printer="]
180       
181        # Initializes the command line tool
182        sender = PyKotMe(doc=__doc__)
183       
184        # parse and checks the command line
185        (options, args) = sender.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1)
186       
187        # sets long options
188        options["help"] = options["h"] or options["help"]
189        options["version"] = options["v"] or options["version"]
190        options["printer"] = options["P"] or options["printer"] or defaults["printer"]
191       
192        if options["help"] :
193            sender.display_usage_and_quit()
194        elif options["version"] :
195            sender.display_version_and_quit()
196        else :
197            retcode = sender.main(args, options)
198    except (PyKotaToolError, PyKotaConfigError, PyKotaStorageError), msg :           
199        sys.stderr.write("%s\n" % msg)
200        sys.stderr.flush()
201        retcode = -1
202
203    try :
204        sender.storage.close()
205    except (TypeError, NameError, AttributeError) :   
206        pass
207       
208    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.