root / pkpgcounter / trunk / pkpgpdls / pjl.py @ 3474

Revision 3474, 5.7 kB (checked in by jerome, 15 years ago)

Changed copyright years.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# -*- coding: utf-8 -*-
2#
3# pkpgcounter : a generic Page Description Language parser
4#
5# (c) 2003-2009 Jerome Alet <alet@librelogiciel.com>
6# This program is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, either version 3 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18#
19# $Id$
20#
21
22"""This modules implements a really minimalist PJL/EJL parser."""
23
24# NOTES : QTY= is the number of collated copies for a job.
25# NOTES : COPIES= is the number of uncollated copies for each page of a job
26
27import sys
28
29class PJLParserError(Exception):
30    """An exception for PJLParser related stuff."""
31    def __init__(self, message = ""):
32        self.message = message
33        Exception.__init__(self, message)
34    def __repr__(self):
35        return self.message
36    __str__ = __repr__
37
38class PJLParser :
39    """A parser for PJL documents.
40
41       Information extracted for bpl11897.pdf which was
42       downloaded from Hewlett-Packard's website.
43    """
44    JL = "PJL"
45    def __init__(self, pjljob, debug=0) :
46        """Initializes JL Parser."""
47        self.debug = debug
48        self.jlmarker = "@%s" % self.JL
49        self.statements = pjljob.replace("\r\n", "\n").split("\n")
50        self.default_variables = {}
51        self.environment_variables = {}
52        self.parsed = 0
53        self.parse()
54
55    def __str__(self) :
56        """Outputs our variables as a string of text."""
57        if not self.parsed :
58            return ""
59        mybuffer = []
60        if self.default_variables :
61            mybuffer.append("Default variables :")
62            for (k, v) in self.default_variables.items() :
63                mybuffer.append("  %s : %s" % (k, v))
64        if self.environment_variables :
65            mybuffer.append("Environment variables :")
66            for (k, v) in self.environment_variables.items() :
67                mybuffer.append("  %s : %s" % (k, v))
68        return "\n".join(mybuffer)
69
70    def logdebug(self, message) :
71        """Logs a debug message if needed."""
72        if self.debug :
73            sys.stderr.write("%s\n" % message)
74
75    def cleanvars(self) :
76        """Cleans the variables dictionnaries."""
77        for dicname in ("default", "environment") :
78            varsdic = getattr(self, "%s_variables" % dicname)
79            for (k, v) in varsdic.items() :
80                if len(v) == 1 :
81                    varsdic[k] = v[0]
82
83    def parse(self) :
84        """Parses a JL job."""
85        for i in range(len(self.statements)) :
86            statement = self.statements[i]
87            if statement.startswith(self.jlmarker) :
88                parts = statement.split()
89                nbparts = len(parts)
90                if parts[0] == self.jlmarker :
91                    # this is a valid JL statement, but we don't
92                    # want to examine all of them...
93                    if (nbparts > 2) \
94                         and ((parts[1].upper() in ("SET", "DEFAULT")) \
95                                  or ((self.jlmarker == "@EJL") and (parts[1].upper() == "JI"))) :
96                        # this is what we are interested in !
97                        try :
98                            (varname, value) = "".join(parts[2:]).split("=", 1) # TODO : parse multiple assignments on the same SET/JI statement
99                        except :
100                            self.logdebug("Invalid JL SET statement [%s]" % repr(statement))
101                        else :
102                            # all still looks fine...
103                            if parts[1].upper() == "DEFAULT" :
104                                varsdic = self.default_variables
105                            else :
106                                varsdic = self.environment_variables
107                            variable = varsdic.setdefault(varname.upper(), [])
108                            variable.append(value)
109                    else :
110                        self.logdebug("Ignored JL statement [%s]" % repr(statement))
111                        self.logdebug(parts)
112                else :
113                    self.logdebug("Invalid JL statement [%s]" % repr(statement))
114            elif (not statement) \
115                  or (statement == r"%-12345X@PJL EOJ") \
116                  or statement[2:].startswith("HP-PCL XL;") :
117                self.logdebug("Ignored JL statement [%s]" % repr(statement))
118            else :
119                self.logdebug("Invalid JL statement [%s]" % repr(statement))
120        self.cleanvars()
121        self.parsed = 1
122        # self.logdebug("%s\n" % str(self))
123
124class EJLParser(PJLParser) :
125    """A parser for EJL (Epson Job Language) documents."""
126    JL = "EJL"
127
128def test() :
129    """Test function."""
130    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
131        sys.argv.append("-")
132    for arg in sys.argv[1:] :
133        klass = PJLParser
134        if arg == "-" :
135            infile = sys.stdin
136            mustclose = False
137        else :
138            if arg.endswith(".ejl") :
139                klass = EJLParser
140            infile = open(arg, "rb")
141            mustclose = True
142        try :
143            parser = klass(infile.read(), debug=1)
144        except PJLParserError, msg :
145            sys.stderr.write("ERROR: %s\n" % msg)
146            sys.stderr.flush()
147        if mustclose :
148            infile.close()
149        sys.stdout.write("%s\n" % str(parser))
150
151if __name__ == "__main__" :
152    test()
Note: See TracBrowser for help on using the browser.