Show
Ignore:
Timestamp:
09/27/08 22:02:37 (16 years ago)
Author:
jerome
Message:

Removed unnecessary spaces at EOL.

Location:
pykota/trunk/pykota/accounters
Files:
6 modified

Legend:

Unmodified
Added
Removed
  • pykota/trunk/pykota/accounters/hardware.py

    r3411 r3413  
    88# the Free Software Foundation, either version 3 of the License, or 
    99# (at your option) any later version. 
    10 #  
     10# 
    1111# This program is distributed in the hope that it will be useful, 
    1212# but WITHOUT ANY WARRANTY; without even the implied warranty of 
    1313# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    1414# GNU General Public License for more details. 
    15 #  
     15# 
    1616# You should have received a copy of the GNU General Public License 
    1717# along with this program.  If not, see <http://www.gnu.org/licenses/>. 
     
    3636        AccounterBase.__init__(self, kotabackend, arguments, ispreaccounter, name) 
    3737        self.isSoftware = 0 
    38          
    39     def getPrinterInternalPageCounter(self) :     
     38 
     39    def getPrinterInternalPageCounter(self) : 
    4040        """Returns the printer's internal page counter.""" 
    4141        self.filter.logdebug("Reading printer %s's internal page counter..." % self.filter.PrinterName) 
    4242        counter = self.askPrinterPageCounter(self.filter.PrinterHostName) 
    4343        self.filter.logdebug("Printer %s's internal page counter value is : %s" % (self.filter.PrinterName, str(counter))) 
    44         return counter     
    45          
    46     def beginJob(self, printer) :     
     44        return counter 
     45 
     46    def beginJob(self, printer) : 
    4747        """Saves printer internal page counter at start of job.""" 
    4848        # save page counter before job 
    4949        self.LastPageCounter = self.getPrinterInternalPageCounter() 
    5050        self.fakeBeginJob() 
    51          
    52     def fakeBeginJob(self) :     
     51 
     52    def fakeBeginJob(self) : 
    5353        """Fakes a begining of a job.""" 
    5454        self.counterbefore = self.getLastPageCounter() 
    55          
    56     def endJob(self, printer) :     
     55 
     56    def endJob(self, printer) : 
    5757        """Saves printer internal page counter at end of job.""" 
    5858        # save page counter after job 
    5959        self.LastPageCounter = self.counterafter = self.getPrinterInternalPageCounter() 
    60          
    61     def getJobSize(self, printer) :     
     60 
     61    def getJobSize(self, printer) : 
    6262        """Returns the actual job size.""" 
    6363        if (not self.counterbefore) or (not self.counterafter) : 
     
    6767                # if there's a previous job, use the last value from database 
    6868                self.filter.printInfo(_("Retrieving printer %s's page counter from database instead.") % printer.Name, "warn") 
    69                 if not self.counterbefore :  
     69                if not self.counterbefore : 
    7070                    self.counterbefore = printer.LastJob.PrinterPageCounter or 0 
    7171                if not self.counterafter : 
    7272                    self.counterafter = printer.LastJob.PrinterPageCounter or 0 
    73                 before = min(self.counterbefore, self.counterafter)     
    74                 after = max(self.counterbefore, self.counterafter)     
     73                before = min(self.counterbefore, self.counterafter) 
     74                after = max(self.counterbefore, self.counterafter) 
    7575                self.counterbefore = before 
    7676                self.counterafter = after 
     
    8585                self.counterbefore = 0 
    8686                self.counterafter = 1 
    87                  
    88         jobsize = (self.counterafter - self.counterbefore)     
     87 
     88        jobsize = (self.counterafter - self.counterbefore) 
    8989        if jobsize < 0 : 
    90             # Try to take care of HP printers  
     90            # Try to take care of HP printers 
    9191            # Their internal page counter is saved to NVRAM 
    9292            # only every 10 pages. If the printer was switched 
    9393            # off then back on during the job, and that the 
    94             # counters difference is negative, we know  
     94            # counters difference is negative, we know 
    9595            # the formula (we can't know if more than eleven 
    9696            # pages were printed though) : 
    9797            if jobsize > -10 : 
    9898                jobsize += 10 
    99             else :     
     99            else : 
    100100                # here we may have got a printer being replaced 
    101101                # DURING the job. This is HIGHLY improbable (but already happened) ! 
     
    104104                jobsize = 1 
    105105        return jobsize 
    106          
     106 
    107107    def askPrinterPageCounter(self, printer) : 
    108108        """Returns the page counter from the printer via an external command. 
    109          
     109 
    110110           The external command must report the life time page number of the printer on stdout. 
    111111        """ 
     
    117117        elif (cmdlower == "pjl") or cmdlower.startswith("pjl:") : 
    118118            return pjl.Handler(self, printer, skipinitialwait).retrieveInternalPageCounter() 
    119              
     119 
    120120        if printer is None : 
    121121            raise PyKotaAccounterError, _("Unknown printer address in HARDWARE(%s) for printer %s") % (commandline, self.filter.PrinterName) 
    122         while 1 :     
     122        while 1 : 
    123123            self.filter.printInfo(_("Launching HARDWARE(%s)...") % commandline) 
    124124            pagecounter = None 
    125             child = popen2.Popen4(commandline)     
     125            child = popen2.Popen4(commandline) 
    126126            try : 
    127127                answer = child.fromchild.read() 
    128             except IOError :     
     128            except IOError : 
    129129                # we were interrupted by a signal, certainely a SIGTERM 
    130130                # caused by the user cancelling the current job 
    131131                try : 
    132132                    os.kill(child.pid, signal.SIGTERM) 
    133                 except :     
     133                except : 
    134134                    pass # already killed ? 
    135135                self.filter.printInfo(_("SIGTERM was sent to hardware accounter %s (pid: %s)") % (commandline, child.pid)) 
    136             else :     
     136            else : 
    137137                lines = [l.strip() for l in answer.split("\n")] 
    138                 for i in range(len(lines)) :  
     138                for i in range(len(lines)) : 
    139139                    try : 
    140140                        pagecounter = int(lines[i]) 
    141141                    except (AttributeError, ValueError) : 
    142142                        self.filter.printInfo(_("Line [%s] skipped in accounter's output. Trying again...") % lines[i]) 
    143                     else :     
     143                    else : 
    144144                        break 
    145             child.fromchild.close()     
     145            child.fromchild.close() 
    146146            child.tochild.close() 
    147147            try : 
    148148                status = child.wait() 
    149             except OSError, msg :     
     149            except OSError, msg : 
    150150                self.filter.logdebug("Error while waiting for hardware accounter pid %s : %s" % (child.pid, msg)) 
    151             else :     
     151            else : 
    152152                if os.WIFEXITED(status) : 
    153153                    status = os.WEXITSTATUS(status) 
    154154                self.filter.printInfo(_("Hardware accounter %s exit code is %s") % (self.arguments, str(status))) 
    155                  
     155 
    156156            if pagecounter is None : 
    157157                message = _("Unable to query printer %s via HARDWARE(%s)") % (printer, commandline) 
     
    159159                    self.filter.printInfo(message, "error") 
    160160                else : 
    161                     raise PyKotaAccounterError, message  
    162             else :         
    163                 return pagecounter         
     161                    raise PyKotaAccounterError, message 
     162            else : 
     163                return pagecounter 
  • pykota/trunk/pykota/accounters/__init__.py

    r3411 r3413  
    88# the Free Software Foundation, either version 3 of the License, or 
    99# (at your option) any later version. 
    10 #  
     10# 
    1111# This program is distributed in the hope that it will be useful, 
    1212# but WITHOUT ANY WARRANTY; without even the implied warranty of 
    1313# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    1414# GNU General Public License for more details. 
    15 #  
     15# 
    1616# You should have received a copy of the GNU General Public License 
    1717# along with this program.  If not, see <http://www.gnu.org/licenses/>. 
  • pykota/trunk/pykota/accounters/ink.py

    r3411 r3413  
    88# the Free Software Foundation, either version 3 of the License, or 
    99# (at your option) any later version. 
    10 #  
     10# 
    1111# This program is distributed in the hope that it will be useful, 
    1212# but WITHOUT ANY WARRANTY; without even the implied warranty of 
    1313# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    1414# GNU General Public License for more details. 
    15 #  
     15# 
    1616# You should have received a copy of the GNU General Public License 
    1717# along with this program.  If not, see <http://www.gnu.org/licenses/>. 
     
    3636                        "GC" : { "G" : "grayscale", "C" : "colored" } , 
    3737                     } 
    38     def computeJobSize(self) :     
     38    def computeJobSize(self) : 
    3939        """Do ink accounting for a print job.""" 
    4040        if (not self.isPreAccounter) and \ 
     
    4646            self.inkUsage = self.filter.preaccounter.inkUsage   # Optimize : already computed ! 
    4747            return self.filter.softwareJobSize                  # Optimize : already computed ! 
    48              
     48 
    4949        parameters = [p.strip() for p in self.arguments.split(',')] 
    5050        if len(parameters) == 1 : 
     
    5454        if colorspace not in ("cmyk", "bw", "cmy", "rgb", "gc") : 
    5555            raise PyKotaAccounterError, _("Invalid parameters for ink accounter : [%s]") % self.arguments 
    56              
    57         try :     
     56 
     57        try : 
    5858            resolution = int(resolution) 
    59         except ValueError :     
     59        except ValueError : 
    6060            raise PyKotaAccounterError, "Invalid parameters for ink accounter : [%s]" % self.arguments 
    61              
     61 
    6262        self.filter.logdebug("Using internal parser to compute job's size and ink usage.") 
    63          
     63 
    6464        jobsize = 0 
    6565        if self.filter.JobSizeBytes : 
    6666            try : 
    6767                from pkpgpdls import analyzer, pdlparser 
    68             except ImportError :     
     68            except ImportError : 
    6969                self.filter.printInfo("pkpgcounter is now distributed separately, please grab it from http://www.pykota.com/software/pkpgcounter", "error") 
    7070                self.filter.printInfo("Precomputed job size will be forced to 0 pages.", "error") 
    71             else :      
     71            else : 
    7272                options = analyzer.AnalyzerOptions(colorspace=colorspace, resolution=resolution) 
    7373                try : 
    7474                    parser = analyzer.PDLAnalyzer(self.filter.DataFile, options) 
    7575                    (cspace, pages) = parser.getInkCoverage() 
    76                 except pdlparser.PDLParserError, msg :     
     76                except pdlparser.PDLParserError, msg : 
    7777                    # Here we just log the failure, but 
    7878                    # we finally ignore it and return 0 since this 
     
    8080                    # job's size MAY be. 
    8181                    self.filter.printInfo(_("Unable to precompute the job's size and ink coverage with the generic PDL analyzer : %s") % msg, "warn") 
    82                 else :     
     82                else : 
    8383                    cspacelabels = self.cspaceExpanded[cspace] 
    8484                    for page in pages : 
     
    8686                        for color in page.keys() : 
    8787                            colordict[cspacelabels[color]] = page[color] 
    88                         self.inkUsage.append(colordict)     
     88                        self.inkUsage.append(colordict) 
    8989                    jobsize = len(pages) 
    9090                    try : 
    9191                        if self.filter.Ticket.FileName is not None : 
    92                             # when a filename is passed as an argument, the backend  
     92                            # when a filename is passed as an argument, the backend 
    9393                            # must generate the correct number of copies. 
    9494                            jobsize *= self.filter.Ticket.Copies 
    9595                            self.inkUsage *= self.filter.Ticket.Copies 
    96                     except AttributeError : # When not run from the cupspykota backend  
     96                    except AttributeError : # When not run from the cupspykota backend 
    9797                        pass 
    9898                    self.filter.logdebug("Ink usage : %s ===> %s" % (cspace, repr(self.inkUsage))) 
    99         return jobsize         
     99        return jobsize 
  • pykota/trunk/pykota/accounters/pjl.py

    r3411 r3413  
    88# the Free Software Foundation, either version 3 of the License, or 
    99# (at your option) any later version. 
    10 #  
     10# 
    1111# This program is distributed in the hope that it will be useful, 
    1212# but WITHOUT ANY WARRANTY; without even the implied warranty of 
    1313# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    1414# GNU General Public License for more details. 
    15 #  
     15# 
    1616# You should have received a copy of the GNU General Public License 
    1717# along with this program.  If not, see <http://www.gnu.org/licenses/>. 
     
    2121# 
    2222 
    23 """This module defines the necessary classes and methods to retrieve  
    24 a printer's internal page counter over a TCP connection."""  
     23"""This module defines the necessary classes and methods to retrieve 
     24a printer's internal page counter over a TCP connection.""" 
    2525 
    2626import sys 
     
    3636 
    3737# Old method : PJLMESSAGE = "\033%-12345X@PJL USTATUSOFF\r\n@PJL INFO STATUS\r\n@PJL INFO PAGECOUNT\r\n\033%-12345X" 
    38 # Here's a new method, which seems to work fine on my HP2300N, while the  
     38# Here's a new method, which seems to work fine on my HP2300N, while the 
    3939# previous one didn't. 
    40 # TODO : We could also experiment with USTATUS JOB=ON and we would know for sure  
     40# TODO : We could also experiment with USTATUS JOB=ON and we would know for sure 
    4141# when the job is finished, without having to poll the printer repeatedly. 
    4242PJLMESSAGE = "\033%-12345X@PJL USTATUS DEVICE=ON\r\n@PJL INFO STATUS\r\n@PJL INFO PAGECOUNT\r\n@PJL USTATUS DEVICE=OFF\033%-12345X" 
     
    5252                    "40000" : "Sleep Mode",             # Standby 
    5353                  } 
    54                    
     54 
    5555class Handler : 
    5656    """A class for PJL print accounting.""" 
     
    6969        self.readthread = None 
    7070        self.quitEvent = threading.Event() 
    71          
    72     def __del__(self) :     
     71 
     72    def __del__(self) : 
    7373        """Ensures the network connection is closed at object deletion time.""" 
    7474        self.close() 
    75          
    76     def open(self) :     
     75 
     76    def open(self) : 
    7777        """Opens the network connection.""" 
    7878        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
     
    9393            self.parent.filter.logdebug("Connected to printer %s:%s" % (self.printerHostname, self.port)) 
    9494            return True 
    95          
    96     def close(self) :     
     95 
     96    def close(self) : 
    9797        """Closes the network connection.""" 
    9898        if not self.closed : 
     
    107107            self.queue = None 
    108108            self.closed = True 
    109              
    110     def readloop(self) :         
     109 
     110    def readloop(self) : 
    111111        """Reading loop thread.""" 
    112112        self.parent.filter.logdebug("Reading thread started.") 
     
    115115            try : 
    116116                answer = self.sock.recv(1) 
    117             except socket.timeout :     
     117            except socket.timeout : 
    118118                pass 
    119119            except socket.error, (dummy, msg) : 
    120120                self.parent.filter.printInfo(_("Problem while receiving PJL answer from %s:%s : %s") % (self.printerHostname, self.port, str(msg)), "warn") 
    121             else :     
     121            else : 
    122122                if answer : 
    123123                    readbuffer.append(answer) 
     
    125125                        self.queue.put("".join(readbuffer)) 
    126126                        readbuffer = [] 
    127         if readbuffer :              
    128             self.queue.put("".join(readbuffer))             
     127        if readbuffer : 
     128            self.queue.put("".join(readbuffer)) 
    129129        self.parent.filter.logdebug("Reading thread ended.") 
    130              
    131     def retrievePJLValues(self) :     
     130 
     131    def retrievePJLValues(self) : 
    132132        """Retrieves a printer's internal page counter and status via PJL.""" 
    133133        while not self.open() : 
     
    141141            except socket.error, msg : 
    142142                self.parent.filter.printInfo(_("Problem while sending PJL query to %s:%s : %s") % (self.printerHostname, self.port, str(msg)), "warn") 
    143             else :     
     143            else : 
    144144                self.parent.filter.logdebug("Query sent to %s : %s" % (self.printerHostname, repr(PJLMESSAGE))) 
    145145                actualpagecount = self.printerStatus = None 
     
    147147                    try : 
    148148                        answer = self.queue.get(True, 5) 
    149                     except Queue.Empty :     
     149                    except Queue.Empty : 
    150150                        self.parent.filter.logdebug("Timeout when reading printer's answer from %s:%s" % (self.printerHostname, self.port)) 
    151                     else :     
     151                    else : 
    152152                        readnext = False 
    153153                        self.parent.filter.logdebug("PJL answer : %s" % repr(answer)) 
    154                         for line in [l.strip() for l in answer.split()] :  
     154                        for line in [l.strip() for l in answer.split()] : 
    155155                            if line.startswith("CODE=") : 
    156156                                self.printerStatus = line.split("=")[1] 
    157157                                self.parent.filter.logdebug("Found status : %s" % self.printerStatus) 
    158                             elif line.startswith("PAGECOUNT=") :     
     158                            elif line.startswith("PAGECOUNT=") : 
    159159                                try : 
    160160                                    actualpagecount = int(line.split('=')[1].strip()) 
    161                                 except ValueError :     
     161                                except ValueError : 
    162162                                    self.parent.filter.logdebug("Received incorrect datas : [%s]" % line.strip()) 
    163163                                else : 
    164164                                    self.parent.filter.logdebug("Found pages counter : %s" % actualpagecount) 
    165                             elif line.startswith("PAGECOUNT") :     
     165                            elif line.startswith("PAGECOUNT") : 
    166166                                readnext = True # page counter is on next line 
    167                             elif readnext :     
     167                            elif readnext : 
    168168                                try : 
    169169                                    actualpagecount = int(line.strip()) 
    170                                 except ValueError :     
     170                                except ValueError : 
    171171                                    self.parent.filter.logdebug("Received incorrect datas : [%s]" % line.strip()) 
    172172                                else : 
     
    174174                                    readnext = False 
    175175                self.printerInternalPageCounter = max(actualpagecount, self.printerInternalPageCounter) 
    176         finally :         
     176        finally : 
    177177            self.close() 
    178          
     178 
    179179    def waitPrinting(self) : 
    180180        """Waits for printer status being 'printing'.""" 
     
    183183        if not noprintingmaxdelay : 
    184184            self.parent.filter.logdebug("Will wait indefinitely until printer %s is in 'printing' state." % self.parent.filter.PrinterName) 
    185         else :     
     185        else : 
    186186            self.parent.filter.logdebug("Will wait until printer %s is in 'printing' state or %i seconds have elapsed." % (self.parent.filter.PrinterName, noprintingmaxdelay)) 
    187187        previousValue = self.parent.getLastPageCounter() 
     
    192192            if self.printerStatus in ('10023', '10003') : 
    193193                break 
    194             if self.printerInternalPageCounter is not None :     
     194            if self.printerInternalPageCounter is not None : 
    195195                if firstvalue is None : 
    196196                    # first time we retrieved a page counter, save it 
    197197                    firstvalue = self.printerInternalPageCounter 
    198                 else :      
     198                else : 
    199199                    # second time (or later) 
    200200                    if firstvalue < self.printerInternalPageCounter : 
     
    213213                                # the printer rejected it for some reason. 
    214214                                self.parent.filter.printInfo("Printer %s probably won't print this job !!!" % self.parent.filter.PrinterName, "warn") 
    215                             else :      
     215                            else : 
    216216                                # Here the job has already been entirely printed, and 
    217217                                # the printer has already passed from 'idle' to 'printing' to 'idle' again. 
     
    220220            self.parent.filter.logdebug(_("Waiting for printer %s to be printing...") % self.parent.filter.PrinterName) 
    221221            time.sleep(statusstabilizationdelay) 
    222          
     222 
    223223    def waitIdle(self) : 
    224224        """Waits for printer status being 'idle'.""" 
     
    233233                   and (os.environ.get("PYKOTAPHASE") == "BEFORE") : 
    234234                    self.parent.filter.logdebug("No need to wait for the printer to be idle, it is the case already.") 
    235                     return  
     235                    return 
    236236                idle_num += 1 
    237237                if idle_num >= statusstabilizationloops : 
    238238                    # printer status is stable, we can exit 
    239239                    break 
    240             else :     
     240            else : 
    241241                idle_num = 0 
    242242            self.parent.filter.logdebug(_("Waiting for printer %s's idle status to stabilize...") % self.parent.filter.PrinterName) 
    243243            time.sleep(statusstabilizationdelay) 
    244      
     244 
    245245    def retrieveInternalPageCounter(self) : 
    246246        """Returns the page counter from the printer via internal PJL handling.""" 
     
    251251               self.parent.filter.JobSizeBytes : 
    252252                self.waitPrinting() 
    253             self.waitIdle()     
    254         except :     
     253            self.waitIdle() 
     254        except : 
    255255            self.parent.filter.printInfo(_("PJL querying stage interrupted. Using latest value seen for internal page counter (%s) on printer %s.") % (self.printerInternalPageCounter, self.parent.filter.PrinterName), "warn") 
    256256            raise 
    257         else :     
     257        else : 
    258258            return self.printerInternalPageCounter 
    259              
     259 
    260260def main(hostname) : 
    261261    """Tries PJL accounting for a printer host.""" 
     
    266266            self.PrinterName = "FakePrintQueue" 
    267267            self.JobSizeBytes = 1 
    268              
     268 
    269269        def printInfo(self, msg, level="info") : 
    270270            """Prints informational message.""" 
    271271            sys.stderr.write("%s : %s\n" % (level.upper(), msg)) 
    272272            sys.stderr.flush() 
    273              
    274         def logdebug(self, msg) :     
     273 
     274        def logdebug(self, msg) : 
    275275            """Prints debug message.""" 
    276276            self.printInfo(msg, "debug") 
    277              
    278     class FakeAccounter :         
     277 
     278    class FakeAccounter : 
    279279        """Fakes an accounter for testing purposes.""" 
    280280        def __init__(self, hostname) : 
     
    283283            self.filter = FakeFilter() 
    284284            self.protocolHandler = Handler(self, hostname) 
    285              
    286         def getLastPageCounter(self) :     
     285 
     286        def getLastPageCounter(self) : 
    287287            """Fakes the return of a page counter.""" 
    288288            return 0 
    289          
     289 
    290290    acc = FakeAccounter(hostname) 
    291291    return acc.protocolHandler.retrieveInternalPageCounter() 
    292      
    293 if __name__ == "__main__" :             
    294     if len(sys.argv) != 2 :     
     292 
     293if __name__ == "__main__" : 
     294    if len(sys.argv) != 2 : 
    295295        sys.stderr.write("Usage :  python  %s  printer_ip_address\n" % sys.argv[0]) 
    296     else :     
     296    else : 
    297297        def _(msg) : 
    298298            """Fake gettext method.""" 
    299299            return msg 
    300              
     300 
    301301        pagecounter = main(sys.argv[1]) 
    302302        print "Internal page counter's value is : %s" % pagecounter 
    303          
     303 
  • pykota/trunk/pykota/accounters/snmp.py

    r3411 r3413  
    88# the Free Software Foundation, either version 3 of the License, or 
    99# (at your option) any later version. 
    10 #  
     10# 
    1111# This program is distributed in the hope that it will be useful, 
    1212# but WITHOUT ANY WARRANTY; without even the implied warranty of 
    1313# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    1414# GNU General Public License for more details. 
    15 #  
     15# 
    1616# You should have received a copy of the GNU General Public License 
    1717# along with this program.  If not, see <http://www.gnu.org/licenses/>. 
     
    3636try : 
    3737    from pysnmp.entity.rfc3413.oneliner import cmdgen 
    38 except ImportError :     
     38except ImportError : 
    3939    hasV4 = False 
    4040    try : 
     
    5050from pykota import constants 
    5151 
    52 #                       
     52# 
    5353# Documentation taken from RFC 3805 (Printer MIB v2) and RFC 2790 (Host Resource MIB) 
    5454# 
     
    6767                       4 : 'testing', 
    6868                       5 : 'down', 
    69                      }   
     69                     } 
    7070hrPrinterDetectedErrorStateOID = "1.3.6.1.2.1.25.3.5.1.2.1" # SNMPv2-SMI::mib-2.25.3.5.1.2.1 
    7171printerDetectedErrorStateValues = [ { 128 : 'Low Paper', 
     
    8787                                        1 : 'Not Assigned in RFC3805', 
    8888                                    }, 
    89                                   ]   
    90                                    
     89                                  ] 
     90 
    9191# The default error mask to use when checking error conditions. 
    9292defaultErrorMask = 0x4fcc # [ 'No Paper', 
     
    100100                          #   'Input Tray Empty', 
    101101                          # ] 
    102                            
    103 # WARNING : some printers don't support this one :                   
     102 
     103# WARNING : some printers don't support this one : 
    104104prtConsoleDisplayBufferTextOID = "1.3.6.1.2.1.43.16.5.1.2.1.1" # SNMPv2-SMI::mib-2.43.16.5.1.2.1.1 
    105105class BaseHandler : 
     
    111111        try : 
    112112            self.community = self.parent.arguments.split(":")[1].strip() 
    113         except IndexError :     
     113        except IndexError : 
    114114            self.community = "public" 
    115115        self.port = 161 
    116116        self.initValues() 
    117          
    118     def initValues(self) :     
     117 
     118    def initValues(self) : 
    119119        """Initializes SNMP values.""" 
    120120        self.printerInternalPageCounter = None 
     
    123123        self.printerDetectedErrorState = None 
    124124        self.timebefore = time.time()   # resets timer also in case of error 
    125          
    126     def retrieveSNMPValues(self) :     
     125 
     126    def retrieveSNMPValues(self) : 
    127127        """Retrieves a printer's internal page counter and status via SNMP.""" 
    128128        raise RuntimeError, "You have to overload this method." 
    129          
    130     def extractErrorStates(self, value) :     
     129 
     130    def extractErrorStates(self, value) : 
    131131        """Returns a list of textual error states from a binary value.""" 
    132132        states = [] 
     
    137137                if byte & k : 
    138138                    states.append(v) 
    139         return states             
    140          
    141     def checkIfError(self, errorstates) :     
     139        return states 
     140 
     141    def checkIfError(self, errorstates) : 
    142142        """Checks if any error state is fatal or not.""" 
    143143        if errorstates is None : 
     
    146146            try : 
    147147                errormask = self.parent.filter.config.getPrinterSNMPErrorMask(self.parent.filter.PrinterName) 
    148             except AttributeError : # debug mode     
     148            except AttributeError : # debug mode 
    149149                errormask = defaultErrorMask 
    150150            if errormask is None : 
     
    161161                    return True 
    162162            self.parent.filter.logdebug("No error condition matching mask 0x%04x" % errormask) 
    163             return False     
    164          
     163            return False 
     164 
    165165    def waitPrinting(self) : 
    166166        """Waits for printer status being 'printing'.""" 
     
    169169        if not noprintingmaxdelay : 
    170170            self.parent.filter.logdebug("Will wait indefinitely until printer %s is in 'printing' state." % self.parent.filter.PrinterName) 
    171         else :     
     171        else : 
    172172            self.parent.filter.logdebug("Will wait until printer %s is in 'printing' state or %i seconds have elapsed." % (self.parent.filter.PrinterName, noprintingmaxdelay)) 
    173173        previousValue = self.parent.getLastPageCounter() 
     
    178178            if statusAsString in ('printing', 'warmup') : 
    179179                break 
    180             if self.printerInternalPageCounter is not None :     
     180            if self.printerInternalPageCounter is not None : 
    181181                if firstvalue is None : 
    182182                    # first time we retrieved a page counter, save it 
    183183                    firstvalue = self.printerInternalPageCounter 
    184                 else :      
     184                else : 
    185185                    # second time (or later) 
    186186                    if firstvalue < self.printerInternalPageCounter : 
     
    205205                                # the printer rejected it for some reason. 
    206206                                self.parent.filter.printInfo("Printer %s probably won't print this job !!!" % self.parent.filter.PrinterName, "warn") 
    207                             else :      
     207                            else : 
    208208                                # Here the job has already been entirely printed, and 
    209209                                # the printer has already passed from 'idle' to 'printing' to 'idle' again. 
    210210                                self.parent.filter.printInfo("Printer %s has probably already printed this job !!!" % self.parent.filter.PrinterName, "warn") 
    211211                            break 
    212             self.parent.filter.logdebug(_("Waiting for printer %s to be printing...") % self.parent.filter.PrinterName)     
     212            self.parent.filter.logdebug(_("Waiting for printer %s to be printing...") % self.parent.filter.PrinterName) 
    213213            time.sleep(statusstabilizationdelay) 
    214          
     214 
    215215    def waitIdle(self) : 
    216216        """Waits for printer status being 'idle'.""" 
     
    228228                          (dstatusAsString == 'running'))) : 
    229229                idle_flag = 1       # Standby / Powersave is considered idle 
    230             if idle_flag :     
     230            if idle_flag : 
    231231                if (self.printerInternalPageCounter is not None) \ 
    232232                   and self.skipinitialwait \ 
    233233                   and (os.environ.get("PYKOTAPHASE") == "BEFORE") : 
    234234                    self.parent.filter.logdebug("No need to wait for the printer to be idle, it is the case already.") 
    235                     return  
     235                    return 
    236236                idle_num += 1 
    237237                if idle_num >= statusstabilizationloops : 
    238238                    # printer status is stable, we can exit 
    239239                    break 
    240             else :     
     240            else : 
    241241                idle_num = 0 
    242             self.parent.filter.logdebug(_("Waiting for printer %s's idle status to stabilize...") % self.parent.filter.PrinterName)     
     242            self.parent.filter.logdebug(_("Waiting for printer %s's idle status to stabilize...") % self.parent.filter.PrinterName) 
    243243            time.sleep(statusstabilizationdelay) 
    244              
     244 
    245245    def retrieveInternalPageCounter(self) : 
    246246        """Returns the page counter from the printer via internal SNMP handling.""" 
     
    251251               self.parent.filter.JobSizeBytes : 
    252252                self.waitPrinting() 
    253             self.waitIdle()     
    254         except :     
     253            self.waitIdle() 
     254        except : 
    255255            self.parent.filter.printInfo(_("SNMP querying stage interrupted. Using latest value seen for internal page counter (%s) on printer %s.") % (self.printerInternalPageCounter, self.parent.filter.PrinterName), "warn") 
    256256            raise 
    257257        return self.printerInternalPageCounter 
    258              
    259 if hasV4 :             
     258 
     259if hasV4 : 
    260260    class Handler(BaseHandler) : 
    261261        """A class for pysnmp v4.x""" 
     
    270270                                                  tuple([int(i) for i in hrDeviceStatusOID.split('.')]), \ 
    271271                                                  tuple([int(i) for i in hrPrinterDetectedErrorStateOID.split('.')])) 
    272             except socket.gaierror, msg :                                       
     272            except socket.gaierror, msg : 
    273273                errorIndication = repr(msg) 
    274             except :                                       
     274            except : 
    275275                errorIndication = "Unknown SNMP/Network error. Check your wires." 
    276             if errorIndication :                                                   
     276            if errorIndication : 
    277277                self.parent.filter.printInfo("SNMP Error : %s" % errorIndication, "error") 
    278278                self.initValues() 
    279             elif errorStatus :     
     279            elif errorStatus : 
    280280                self.parent.filter.printInfo("SNMP Error : %s at %s" % (errorStatus.prettyPrint(), \ 
    281281                                                                        varBinds[int(errorIndex)-1]), \ 
    282282                                             "error") 
    283283                self.initValues() 
    284             else :                                  
     284            else : 
    285285                self.printerInternalPageCounter = max(self.printerInternalPageCounter, int(varBinds[0][1].prettyPrint() or "0")) 
    286286                self.printerStatus = int(varBinds[1][1].prettyPrint()) 
     
    295295    class Handler(BaseHandler) : 
    296296        """A class for pysnmp v3.4.x""" 
    297         def retrieveSNMPValues(self) :     
     297        def retrieveSNMPValues(self) : 
    298298            """Retrieves a printer's internal page counter and status via SNMP.""" 
    299299            ver = alpha.protoVersions[alpha.protoVersionId1] 
     
    310310                                   (self.printerHostname, self.port), \ 
    311311                                   (self.handleAnswer, req)) 
    312             except (SnmpOverUdpError, select.error), msg :     
     312            except (SnmpOverUdpError, select.error), msg : 
    313313                self.parent.filter.printInfo(_("Network error while doing SNMP queries on printer %s : %s") % (self.printerHostname, msg), "warn") 
    314314                self.initValues() 
    315315            tsp.close() 
    316          
     316 
    317317        def handleAnswer(self, wholeMsg, notusedhere, req): 
    318318            """Decodes and handles the SNMP answer.""" 
     
    321321            try : 
    322322                rsp.berDecode(wholeMsg) 
    323             except TypeMismatchError, msg :     
     323            except TypeMismatchError, msg : 
    324324                self.parent.filter.printInfo(_("SNMP message decoding error for printer %s : %s") % (self.printerHostname, msg), "warn") 
    325325                self.initValues() 
     
    333333                        for varBind in rsp.apiAlphaGetPdu().apiAlphaGetVarBindList(): 
    334334                            self.values.append(varBind.apiAlphaGetOidVal()[1].rawAsn1Value) 
    335                         try :     
     335                        try : 
    336336                            # keep maximum value seen for printer's internal page counter 
    337337                            self.printerInternalPageCounter = max(self.printerInternalPageCounter, self.values[0]) 
     
    344344                                    deviceStatusValues.get(self.deviceStatus), \ 
    345345                                    self.printerDetectedErrorState)) 
    346                         except IndexError :     
     346                        except IndexError : 
    347347                            self.parent.filter.logdebug("SNMP answer is incomplete : %s" % str(self.values)) 
    348348                            pass 
    349                         else :     
     349                        else : 
    350350                            return 1 
    351                      
     351 
    352352def main(hostname) : 
    353353    """Tries SNMP accounting for a printer host.""" 
     
    358358            self.PrinterName = "FakePrintQueue" 
    359359            self.JobSizeBytes = 1 
    360              
     360 
    361361        def printInfo(self, msg, level="info") : 
    362362            """Prints informational message.""" 
    363363            sys.stderr.write("%s : %s\n" % (level.upper(), msg)) 
    364364            sys.stderr.flush() 
    365              
    366         def logdebug(self, msg) :     
     365 
     366        def logdebug(self, msg) : 
    367367            """Prints debug message.""" 
    368368            self.printInfo(msg, "debug") 
    369              
    370     class fakeAccounter :         
     369 
     370    class fakeAccounter : 
    371371        """Fakes an accounter for testing purposes.""" 
    372372        def __init__(self) : 
     
    375375            self.filter = fakeFilter() 
    376376            self.protocolHandler = Handler(self, hostname) 
    377              
    378         def getLastPageCounter(self) :     
     377 
     378        def getLastPageCounter(self) : 
    379379            """Fakes the return of a page counter.""" 
    380380            return 0 
    381          
    382     acc = fakeAccounter()             
     381 
     382    acc = fakeAccounter() 
    383383    return acc.protocolHandler.retrieveInternalPageCounter() 
    384          
    385 if __name__ == "__main__" :             
    386     if len(sys.argv) != 2 :     
     384 
     385if __name__ == "__main__" : 
     386    if len(sys.argv) != 2 : 
    387387        sys.stderr.write("Usage :  python  %s  printer_ip_address\n" % sys.argv[0]) 
    388     else :     
     388    else : 
    389389        def _(msg) : 
    390390            return msg 
    391              
     391 
    392392        pagecounter = main(sys.argv[1]) 
    393393        print "Internal page counter's value is : %s" % pagecounter 
  • pykota/trunk/pykota/accounters/software.py

    r3411 r3413  
    88# the Free Software Foundation, either version 3 of the License, or 
    99# (at your option) any later version. 
    10 #  
     10# 
    1111# This program is distributed in the hope that it will be useful, 
    1212# but WITHOUT ANY WARRANTY; without even the implied warranty of 
    1313# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    1414# GNU General Public License for more details. 
    15 #  
     15# 
    1616# You should have received a copy of the GNU General Public License 
    1717# along with this program.  If not, see <http://www.gnu.org/licenses/>. 
     
    3030 
    3131class Accounter(AccounterBase) : 
    32     def computeJobSize(self) :     
     32    def computeJobSize(self) : 
    3333        """Feeds an external command with our datas to let it compute the job size, and return its value.""" 
    3434        if (not self.isPreAccounter) and \ 
     
    3939            self.filter.logdebug("Precomputing pass told us that job is %s pages long." % self.filter.softwareJobSize) 
    4040            return self.filter.softwareJobSize   # Optimize : already computed ! 
    41              
     41 
    4242        if self.arguments : 
    4343            self.filter.logdebug("Using external script %s to compute job's size." % self.arguments) 
    4444            return self.withExternalScript() 
    45         else :     
     45        else : 
    4646            self.filter.logdebug("Using internal parser to compute job's size.") 
    4747            return self.withInternalParser() 
    48          
    49     def withInternalParser(self) :     
     48 
     49    def withInternalParser(self) : 
    5050        """Does software accounting through an external script.""" 
    5151        jobsize = 0 
     
    5353            try : 
    5454                from pkpgpdls import analyzer, pdlparser 
    55             except ImportError :     
     55            except ImportError : 
    5656                self.filter.printInfo("pkpgcounter is now distributed separately, please grab it from http://www.pykota.com/software/pkpgcounter", "error") 
    5757                self.filter.printInfo("Precomputed job size will be forced to 0 pages.", "error") 
    58             else :      
     58            else : 
    5959                try : 
    6060                    parser = analyzer.PDLAnalyzer(self.filter.DataFile) 
    6161                    jobsize = parser.getJobSize() 
    62                 except pdlparser.PDLParserError, msg :     
     62                except pdlparser.PDLParserError, msg : 
    6363                    # Here we just log the failure, but 
    6464                    # we finally ignore it and return 0 since this 
     
    6666                    # job's size MAY be. 
    6767                    self.filter.printInfo(_("Unable to precompute the job's size with the generic PDL analyzer : %s") % msg, "warn") 
    68                 else :     
     68                else : 
    6969                    try : 
    7070                        if self.filter.Ticket.FileName is not None : 
    71                             # when a filename is passed as an argument, the backend  
     71                            # when a filename is passed as an argument, the backend 
    7272                            # must generate the correct number of copies. 
    7373                            jobsize *= self.filter.Ticket.Copies 
    7474                    except AttributeError : # When not run from the cupspykota backend 
    7575                        pass 
    76         return jobsize         
    77                  
    78     def withExternalScript(self) :     
     76        return jobsize 
     77 
     78    def withExternalScript(self) : 
    7979        """Does software accounting through an external script.""" 
    8080        self.filter.logdebug(_("Launching SOFTWARE(%s)...") % self.arguments) 
     
    8383        try : 
    8484            answer = child.read() 
    85         except (IOError, OSError), msg :     
    86             msg = "%s : %s" % (self.arguments, msg)  
     85        except (IOError, OSError), msg : 
     86            msg = "%s : %s" % (self.arguments, msg) 
    8787            self.filter.printInfo(_("Unable to compute job size with accounter %s") % msg, "warn") 
    88         else :     
     88        else : 
    8989            lines = [l.strip() for l in answer.split("\n")] 
    90             for i in range(len(lines)) :  
     90            for i in range(len(lines)) : 
    9191                try : 
    9292                    pagecounter = int(lines[i]) 
    9393                except (AttributeError, ValueError) : 
    9494                    self.filter.logdebug(_("Line [%s] skipped in accounter's output. Trying again...") % lines[i]) 
    95                 else :     
     95                else : 
    9696                    break 
    97                      
     97 
    9898        status = child.close() 
    9999        try : 
    100100            if os.WIFEXITED(status) : 
    101101                status = os.WEXITSTATUS(status) 
    102         except TypeError :         
     102        except TypeError : 
    103103            pass # None means no error occured. 
    104104        self.filter.logdebug(_("Software accounter %s exit code is %s") % (self.arguments, str(status))) 
    105              
    106         if pagecounter is None :     
     105 
     106        if pagecounter is None : 
    107107            message = _("Unable to compute job size with accounter %s") % self.arguments 
    108108            if self.onerror == "CONTINUE" : 
     
    111111                raise PyKotaAccounterError, message 
    112112        self.filter.logdebug("Software accounter %s said job is %s pages long." % (self.arguments, repr(pagecounter))) 
    113              
    114         pagecounter = pagecounter or 0     
     113 
     114        pagecounter = pagecounter or 0 
    115115        try : 
    116116            if self.filter.Ticket.FileName is not None : 
    117                 # when a filename is passed as an argument, the backend  
     117                # when a filename is passed as an argument, the backend 
    118118                # must generate the correct number of copies. 
    119119                pagecounter *= self.filter.Ticket.Copies 
    120         except AttributeError :         
     120        except AttributeError : 
    121121            pass # when called from pykotme. TODO : clean this mess some day. 
    122                          
     122 
    123123        return pagecounter