shlex.py 10.8 KB
Newer Older
1 2
"""A lexical analyzer class for simple shell-like syntaxes."""

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

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

13
from io import StringIO
14 15

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

17
class shlex:
Tim Peters's avatar
Tim Peters committed
18
    "A lexical analyzer class for simple shell-like syntaxes."
19
    def __init__(self, instream=None, infile=None, posix=False):
20
        if isinstance(instream, str):
21
            instream = StringIO(instream)
22
        if instream is not None:
23
            self.instream = instream
Guido van Rossum's avatar
Guido van Rossum committed
24
            self.infile = infile
25 26
        else:
            self.instream = sys.stdin
Guido van Rossum's avatar
Guido van Rossum committed
27
            self.infile = None
28 29 30 31 32
        self.posix = posix
        if posix:
            self.eof = None
        else:
            self.eof = ''
33
        self.commenters = '#'
Fred Drake's avatar
Fred Drake committed
34 35
        self.wordchars = ('abcdfeghijklmnopqrstuvwxyz'
                          'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_')
36
        if self.posix:
37 38
            self.wordchars += ('ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
                               'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ')
39
        self.whitespace = ' \t\r\n'
40
        self.whitespace_split = False
41
        self.quotes = '\'"'
42 43
        self.escape = '\\'
        self.escapedquotes = '"'
44
        self.state = ' '
45
        self.pushback = deque()
46 47 48
        self.lineno = 1
        self.debug = 0
        self.token = ''
49
        self.filestack = deque()
Guido van Rossum's avatar
Guido van Rossum committed
50 51
        self.source = None
        if self.debug:
52 53
            print('shlex: reading from %s, line %d' \
                  % (self.instream, self.lineno))
54 55 56

    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
57
        if self.debug >= 1:
58
            print("shlex: pushing token " + repr(tok))
59
        self.pushback.appendleft(tok)
60

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

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

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

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

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

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

261 262 263
    def __iter__(self):
        return self

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

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

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