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

Revision 455, 5.3 kB (checked in by jerome, 17 years ago)

Fixed PJL reference's file name.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[252]1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3#
4# pkpgcounter : a generic Page Description Language parser
5#
[443]6# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
[252]7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23
[357]24"""This modules implements a really minimalist PJL parser."""
25
[454]26# NOTES : QTY= is the number of collated copies for a job.
27# NOTES : COPIES= is the number of uncollated copies for each page of a job
28
[252]29import sys
30
31class PJLParserError(Exception):
32    """An exception for PJLParser related stuff."""
33    def __init__(self, message = ""):
34        self.message = message
35        Exception.__init__(self, message)
36    def __repr__(self):
37        return self.message
38    __str__ = __repr__
39       
40class PJLParser :
41    """A parser for PJL documents.
42   
[455]43       Information extracted for bpl11897.pdf which was
[454]44       downloaded from Hewlett-Packard's website.
45   
[252]46       Only extracts the PJL SET variables. Ignore other statements.
47    """
48    def __init__(self, pjljob, debug=0) :
49        """Initializes PJL Parser."""
50        self.debug = debug
51        self.statements = pjljob.replace("\r\n", "\n").split("\n")
52        self.default_variables = {}
53        self.environment_variables = {}
54        self.parsed = 0
55        self.parse()
56       
57    def __str__(self) :   
58        """Outputs our variables as a string of text."""
59        if not self.parsed :
60            return ""
61        mybuffer = []
62        if self.default_variables :
63            mybuffer.append("Default variables :")
64            for (k, v) in self.default_variables.items() :
65                mybuffer.append("  %s : %s" % (k, v))
66        if self.environment_variables :       
67            mybuffer.append("Environment variables :")
68            for (k, v) in self.environment_variables.items() :
69                mybuffer.append("  %s : %s" % (k, v))
70        return "\n".join(mybuffer)       
71           
72    def logdebug(self, message) :   
73        """Logs a debug message if needed."""
74        if self.debug :
75            sys.stderr.write("%s\n" % message)
76           
77    def cleanvars(self) :       
78        """Cleans the variables dictionnaries."""
79        for dicname in ("default", "environment") :
80            varsdic = getattr(self, "%s_variables" % dicname)
81            for (k, v) in varsdic.items() :
82                if len(v) == 1 :
83                    varsdic[k] = v[0]
84       
85    def parse(self) :
86        """Parses a PJL job."""
87        for i in range(len(self.statements)) :
88            statement = self.statements[i]
89            if statement.startswith("@PJL") :
90                parts = statement.split()
91                nbparts = len(parts)
92                if parts[0] == "@PJL" :
93                    # this is a valid PJL statement, but we don't
94                    # want to examine all of them...
95                    if (nbparts > 2) and (parts[1].upper() in ("SET", "DEFAULT")) :
96                        # this is what we are interested in !
97                        try :   
98                            (varname, value) = "".join(parts[2:]).split("=", 1)
99                        except :   
100                            self.logdebug("Invalid PJL 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 PJL statement [%s]" % repr(statement))
111                else :
112                    self.logdebug("Invalid PJL statement [%s]" % repr(statement))
113            else :
114                self.logdebug("Invalid PJL statement [%s]" % repr(statement))
115        self.cleanvars()
116        self.parsed = 1
117       
118def test() :       
119    """Test function."""
120    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
121        sys.argv.append("-")
122    for arg in sys.argv[1:] :
123        if arg == "-" :
124            infile = sys.stdin
125            mustclose = 0
126        else :   
127            infile = open(arg, "rb")
128            mustclose = 1
129        try :
130            parser = PJLParser(infile.read(), debug=1)
131        except PJLParserError, msg :   
132            sys.stderr.write("ERROR: %s\n" % msg)
133            sys.stderr.flush()
134        if mustclose :   
135            infile.close()
136        print str(parser)           
137   
138if __name__ == "__main__" :   
139    test()
Note: See TracBrowser for help on using the browser.