root / pkpgcounter / trunk / pdlanalyzer / analyzer.py @ 226

Revision 226, 5.6 kB (checked in by jerome, 19 years ago)

Added -d for debug mode

  • Property svn:keywords set to Auth Date Id Rev
Line 
1#
2# pkpgcounter : a generic Page Description Language parser
3#
4# (c) 2003, 2004, 2005 Jerome Alet <alet@librelogiciel.com>
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation; either version 2 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program; if not, write to the Free Software
17# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18#
19# $Id$
20#
21
22import sys
23import tempfile
24
25from pdlanalyzer import version, pdlparser, postscript, pdf, pcl345, pclxl, escp2, dvi, tiff
26
27class PDLAnalyzer :   
28    """Class for PDL autodetection."""
29    def __init__(self, filename, debug=0) :
30        """Initializes the PDL analyzer.
31       
32           filename is the name of the file or '-' for stdin.
33           filename can also be a file-like object which
34           supports read() and seek().
35        """
36        self.debug = debug
37        self.filename = filename
38       
39    def getJobSize(self) :   
40        """Returns the job's size."""
41        self.openFile()
42        try :
43            pdlhandler = self.detectPDLHandler()
44        except pdlparser.PDLParserError, msg :   
45            self.closeFile()
46            raise pdlparser.PDLParserError, "Unknown file format for %s (%s)" % (self.filename, msg)
47        else :
48            try :
49                size = pdlhandler.getJobSize()
50            finally :   
51                self.closeFile()
52            return size
53       
54    def openFile(self) :   
55        """Opens the job's data stream for reading."""
56        self.mustclose = 0  # by default we don't want to close the file when finished
57        if hasattr(self.filename, "read") and hasattr(self.filename, "seek") :
58            # filename is in fact a file-like object
59            infile = self.filename
60        elif self.filename == "-" :
61            # we must read from stdin
62            infile = sys.stdin
63        else :   
64            # normal file
65            self.infile = open(self.filename, "rb")
66            self.mustclose = 1
67            return
68           
69        # Use a temporary file, always seekable contrary to standard input.
70        self.infile = tempfile.TemporaryFile(mode="w+b")
71        while 1 :
72            data = infile.read(pdlparser.MEGABYTE) 
73            if not data :
74                break
75            self.infile.write(data)
76        self.infile.flush()   
77        self.infile.seek(0)
78           
79    def closeFile(self) :       
80        """Closes the job's data stream if we can close it."""
81        if self.mustclose :
82            self.infile.close()   
83        else :   
84            # if we don't have to close the file, then
85            # ensure the file pointer is reset to the
86            # start of the file in case the process wants
87            # to read the file again.
88            try :
89                self.infile.seek(0)
90            except :   
91                pass    # probably stdin, which is not seekable
92       
93    def detectPDLHandler(self) :   
94        """Tries to autodetect the document format.
95       
96           Returns the correct PDL handler class or None if format is unknown
97        """   
98        # Try to detect file type by reading first and last blocks of datas   
99        # Each parser can read them automatically, but here we do this only once.
100        self.infile.seek(0)
101        firstblock = self.infile.read(pdlparser.FIRSTBLOCKSIZE)
102        try :
103            self.infile.seek(-pdlparser.LASTBLOCKSIZE, 2)
104            lastblock = self.infile.read(pdlparser.LASTBLOCKSIZE)
105        except IOError :   
106            lastblock = ""
107        self.infile.seek(0)
108        if not firstblock :
109            raise pdlparser.PDLParserError, "input file %s is empty !" % str(self.filename)
110        else :   
111            for module in (postscript, \
112                           pclxl, \
113                           pdf, \
114                           pcl345, \
115                           escp2, \
116                           dvi, \
117                           tiff) :
118                try :               
119                    return getattr(module, "Parser")(self.infile, self.debug, firstblock, lastblock)
120                except pdlparser.PDLParserError :
121                    pass # try next parser
122        raise pdlparser.PDLParserError, "Analysis of first data block failed."
123           
124def main() :   
125    """Entry point for PDL Analyzer."""
126    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
127        sys.argv.append("-")
128       
129    if ("-h" in sys.argv[1:]) or ("--help" in sys.argv[1:]) :
130        print "usage : pkpgcounter file1 file2 ... fileN"
131    elif ("-v" in sys.argv[1:]) or ("--version" in sys.argv[1:]) :
132        print "%s" % version.__version__
133    else :
134        totalsize = 0   
135        debug = 0
136        minindex = 1
137        if sys.argv[1] in ("-d", "--debug") :
138            minindex = 2
139            debug = 1
140        for arg in sys.argv[minindex:] :
141            try :
142                parser = PDLAnalyzer(arg, debug)
143                totalsize += parser.getJobSize()
144            except pdlparser.PDLParserError, msg :   
145                sys.stderr.write("ERROR: %s\n" % msg)
146                sys.stderr.flush()
147        print "%s" % totalsize
148   
149if __name__ == "__main__" :   
150    main()
Note: See TracBrowser for help on using the browser.