shlex.py 10.8 KB
Newer Older
1
# -*- coding: iso-8859-1 -*-
2 3
"""A lexical analyzer class for simple shell-like syntaxes."""

Tim Peters's avatar
Tim Peters committed
4
# Module and documentation by Eric S. Raymond, 21 Dec 1998
Guido van Rossum's avatar
Guido van Rossum committed
5
# Input stacking and error message cleanup added by ESR, March 2000
Tim Peters's avatar
Tim Peters committed
6
# push_source() and pop_source() made explicit by ESR, January 2001.
7 8
# Posix compliance, split(), string arguments, and
# iterator interface by Gustavo Niemeyer, April 2003.
9

10
import os.path
11
import sys
12
from collections import deque
13

14
from io import StringIO
15 16

__all__ = ["shlex", "split"]
17

18
class shlex:
Tim Peters's avatar
Tim Peters committed
19
    "A lexical analyzer class for simple shell-like syntaxes."
20
    def __init__(self, instream=None, infile=None, posix=False):
21
        if isinstance(instream, str):
22
            instream = StringIO(instream)
23
        if instream is not None:
24
            self.instream = instream
Guido van Rossum's avatar
Guido van Rossum committed
25
            self.infile = infile
26 27
        else:
            self.instream = sys.stdin
Guido van Rossum's avatar
Guido van Rossum committed
28
            self.infile = None
29 30 31 32 33
        self.posix = posix
        if posix:
            self.eof = None
        else:
            self.eof = ''
34
        self.commenters = '#'
Fred Drake's avatar
Fred Drake committed
35 36
        self.wordchars = ('abcdfeghijklmnopqrstuvwxyz'
                          'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_')
37 38 39
        if self.posix:
            self.wordchars += (''
                               '')
40
        self.whitespace = ' \t\r\n'
41
        self.whitespace_split = False
42
        self.quotes = '\'"'
43 44
        self.escape = '\\'
        self.escapedquotes = '"'
45
        self.state = ' '
46
        self.pushback = deque()
47 48 49
        self.lineno = 1
        self.debug = 0
        self.token = ''
50
        self.filestack = deque()
Guido van Rossum's avatar
Guido van Rossum committed
51 52
        self.source = None
        if self.debug:
53 54
            print('shlex: reading from %s, line %d' \
                  % (self.instream, self.lineno))
55 56 57

    def push_token(self, tok):
        "Push a token onto the stack popped by the get_token method"
Guido van Rossum's avatar
Guido van Rossum committed
58
        if self.debug >= 1:
59
            print("shlex: pushing token " + repr(tok))
60
        self.pushback.appendleft(tok)
61

62 63
    def push_source(self, newstream, newfile=None):
        "Push an input source onto the lexer's input source stack."
64
        if isinstance(newstream, str):
65
            newstream = StringIO(newstream)
66
        self.filestack.appendleft((self.infile, self.instream, self.lineno))
67 68 69 70
        self.infile = newfile
        self.instream = newstream
        self.lineno = 1
        if self.debug:
71
            if newfile is not None:
72
                print('shlex: pushing to file %s' % (self.infile,))
73
            else:
74
                print('shlex: pushing to stream %s' % (self.instream,))
75 76 77 78

    def pop_source(self):
        "Pop the input source stack."
        self.instream.close()
79
        (self.infile, self.instream, self.lineno) = self.filestack.popleft()
80
        if self.debug:
81 82
            print('shlex: popping to %s, line %d' \
                  % (self.instream, self.lineno))
83 84
        self.state = ' '

85
    def get_token(self):
Guido van Rossum's avatar
Guido van Rossum committed
86
        "Get a token from the input stream (or from stack if it's nonempty)"
87
        if self.pushback:
88
            tok = self.pushback.popleft()
Guido van Rossum's avatar
Guido van Rossum committed
89
            if self.debug >= 1:
90
                print("shlex: popping token " + repr(tok))
91
            return tok
Fred Drake's avatar
Fred Drake committed
92
        # No pushback.  Get a token.
Guido van Rossum's avatar
Guido van Rossum committed
93 94
        raw = self.read_token()
        # Handle inclusions
95 96 97 98 99 100 101
        if self.source is not None:
            while raw == self.source:
                spec = self.sourcehook(self.read_token())
                if spec:
                    (newfile, newstream) = spec
                    self.push_source(newstream, newfile)
                raw = self.get_token()
Guido van Rossum's avatar
Guido van Rossum committed
102
        # Maybe we got EOF instead?
103
        while raw == self.eof:
104
            if not self.filestack:
105
                return self.eof
Guido van Rossum's avatar
Guido van Rossum committed
106
            else:
107
                self.pop_source()
Guido van Rossum's avatar
Guido van Rossum committed
108
                raw = self.get_token()
109
        # Neither inclusion nor EOF
Guido van Rossum's avatar
Guido van Rossum committed
110
        if self.debug >= 1:
111
            if raw != self.eof:
112
                print("shlex: token=" + repr(raw))
Guido van Rossum's avatar
Guido van Rossum committed
113
            else:
114
                print("shlex: token=EOF")
Guido van Rossum's avatar
Guido van Rossum committed
115 116 117
        return raw

    def read_token(self):
118
        quoted = False
119
        escapedstate = ' '
120
        while True:
121
            nextchar = self.instream.read(1)
122 123 124
            if nextchar == '\n':
                self.lineno = self.lineno + 1
            if self.debug >= 3:
125 126
                print("shlex: in state", repr(self.state), \
                      "I see character:", repr(nextchar))
Fred Drake's avatar
Fred Drake committed
127
            if self.state is None:
128
                self.token = ''        # past end of file
Guido van Rossum's avatar
Guido van Rossum committed
129
                break
130 131
            elif self.state == ' ':
                if not nextchar:
132
                    self.state = None  # end of file
133 134 135
                    break
                elif nextchar in self.whitespace:
                    if self.debug >= 2:
136
                        print("shlex: I see whitespace in whitespace state")
137
                    if self.token or (self.posix and quoted):
Fred Drake's avatar
Fred Drake committed
138
                        break   # emit current token
139 140 141 142 143
                    else:
                        continue
                elif nextchar in self.commenters:
                    self.instream.readline()
                    self.lineno = self.lineno + 1
144 145 146
                elif self.posix and nextchar in self.escape:
                    escapedstate = 'a'
                    self.state = nextchar
147 148 149 150
                elif nextchar in self.wordchars:
                    self.token = nextchar
                    self.state = 'a'
                elif nextchar in self.quotes:
151 152
                    if not self.posix:
                        self.token = nextchar
153
                    self.state = nextchar
154 155 156
                elif self.whitespace_split:
                    self.token = nextchar
                    self.state = 'a'
157 158
                else:
                    self.token = nextchar
159
                    if self.token or (self.posix and quoted):
Fred Drake's avatar
Fred Drake committed
160
                        break   # emit current token
161 162 163
                    else:
                        continue
            elif self.state in self.quotes:
164
                quoted = True
165
                if not nextchar:      # end of file
166
                    if self.debug >= 2:
167
                        print("shlex: I see EOF in quotes state")
168
                    # XXX what error should be raised here?
169
                    raise ValueError("No closing quotation")
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
                if nextchar == self.state:
                    if not self.posix:
                        self.token = self.token + nextchar
                        self.state = ' '
                        break
                    else:
                        self.state = 'a'
                elif self.posix and nextchar in self.escape and \
                     self.state in self.escapedquotes:
                    escapedstate = self.state
                    self.state = nextchar
                else:
                    self.token = self.token + nextchar
            elif self.state in self.escape:
                if not nextchar:      # end of file
                    if self.debug >= 2:
186
                        print("shlex: I see EOF in escape state")
187
                    # XXX what error should be raised here?
188
                    raise ValueError("No escaped character")
189 190 191 192 193 194 195
                # In posix shells, only the quote itself or the escape
                # character may be escaped within quotes.
                if escapedstate in self.quotes and \
                   nextchar != self.state and nextchar != escapedstate:
                    self.token = self.token + self.state
                self.token = self.token + nextchar
                self.state = escapedstate
196 197
            elif self.state == 'a':
                if not nextchar:
Tim Peters's avatar
Tim Peters committed
198
                    self.state = None   # end of file
199 200 201
                    break
                elif nextchar in self.whitespace:
                    if self.debug >= 2:
202
                        print("shlex: I see whitespace in word state")
203
                    self.state = ' '
204
                    if self.token or (self.posix and quoted):
Fred Drake's avatar
Fred Drake committed
205
                        break   # emit current token
206 207 208 209 210
                    else:
                        continue
                elif nextchar in self.commenters:
                    self.instream.readline()
                    self.lineno = self.lineno + 1
211 212 213 214 215 216 217 218 219 220 221 222 223
                    if self.posix:
                        self.state = ' '
                        if self.token or (self.posix and quoted):
                            break   # emit current token
                        else:
                            continue
                elif self.posix and nextchar in self.quotes:
                    self.state = nextchar
                elif self.posix and nextchar in self.escape:
                    escapedstate = 'a'
                    self.state = nextchar
                elif nextchar in self.wordchars or nextchar in self.quotes \
                    or self.whitespace_split:
224 225
                    self.token = self.token + nextchar
                else:
226
                    self.pushback.appendleft(nextchar)
227
                    if self.debug >= 2:
228
                        print("shlex: I see punctuation in word state")
229
                    self.state = ' '
230
                    if self.token:
Fred Drake's avatar
Fred Drake committed
231
                        break   # emit current token
232 233 234 235
                    else:
                        continue
        result = self.token
        self.token = ''
236 237
        if self.posix and not quoted and result == '':
            result = None
Guido van Rossum's avatar
Guido van Rossum committed
238 239
        if self.debug > 1:
            if result:
240
                print("shlex: raw token=" + repr(result))
Guido van Rossum's avatar
Guido van Rossum committed
241
            else:
242
                print("shlex: raw token=EOF")
243 244
        return result

Guido van Rossum's avatar
Guido van Rossum committed
245 246 247 248
    def sourcehook(self, newfile):
        "Hook called on a filename to be sourced."
        if newfile[0] == '"':
            newfile = newfile[1:-1]
249
        # This implements cpp-like semantics for relative-path inclusion.
250
        if isinstance(self.infile, str) and not os.path.isabs(newfile):
251
            newfile = os.path.join(os.path.dirname(self.infile), newfile)
Guido van Rossum's avatar
Guido van Rossum committed
252 253
        return (newfile, open(newfile, "r"))

Guido van Rossum's avatar
Guido van Rossum committed
254 255
    def error_leader(self, infile=None, lineno=None):
        "Emit a C-compiler-like, Emacs-friendly error-message leader."
256
        if infile is None:
Guido van Rossum's avatar
Guido van Rossum committed
257
            infile = self.infile
258
        if lineno is None:
Guido van Rossum's avatar
Guido van Rossum committed
259 260 261
            lineno = self.lineno
        return "\"%s\", line %d: " % (infile, lineno)

262 263 264
    def __iter__(self):
        return self

265
    def __next__(self):
266 267 268 269 270
        token = self.get_token()
        if token == self.eof:
            raise StopIteration
        return token

271 272
def split(s, comments=False, posix=True):
    lex = shlex(s, posix=posix)
273 274 275
    lex.whitespace_split = True
    if not comments:
        lex.commenters = ''
276
    return list(lex)
277

Tim Peters's avatar
Tim Peters committed
278
if __name__ == '__main__':
279 280 281 282 283
    if len(sys.argv) == 1:
        lexer = shlex()
    else:
        file = sys.argv[1]
        lexer = shlex(open(file), file)
284 285
    while 1:
        tt = lexer.get_token()
286
        if tt:
287
            print("Token: " + repr(tt))
288
        else:
289
            break