blob: 0113fb7db37378fcb0a179c484b8976291a9f489 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`shlex` --- Simple lexical analysis
2========================================
3
4.. module:: shlex
5 :synopsis: Simple lexical analysis for Unix shell-like languages.
6.. moduleauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
7.. moduleauthor:: Gustavo Niemeyer <niemeyer@conectiva.com>
8.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
9.. sectionauthor:: Gustavo Niemeyer <niemeyer@conectiva.com>
10
Raymond Hettingera1993682011-01-27 01:20:32 +000011**Source code:** :source:`Lib/shlex.py`
12
13--------------
Georg Brandl116aa622007-08-15 14:28:22 +000014
Georg Brandl116aa622007-08-15 14:28:22 +000015The :class:`shlex` class makes it easy to write lexical analyzers for simple
16syntaxes resembling that of the Unix shell. This will often be useful for
17writing minilanguages, (for example, in run control files for Python
18applications) or for parsing quoted strings.
19
Georg Brandl116aa622007-08-15 14:28:22 +000020The :mod:`shlex` module defines the following functions:
21
22
Georg Brandl18244152009-09-02 20:34:52 +000023.. function:: split(s, comments=False, posix=True)
Georg Brandl116aa622007-08-15 14:28:22 +000024
25 Split the string *s* using shell-like syntax. If *comments* is :const:`False`
26 (the default), the parsing of comments in the given string will be disabled
Senthil Kumarana6bac952011-07-04 11:28:30 -070027 (setting the :attr:`commenters` attribute of the :class:`shlex` instance to
28 the empty string). This function operates in POSIX mode by default, but uses
Georg Brandl116aa622007-08-15 14:28:22 +000029 non-POSIX mode if the *posix* argument is false.
30
Georg Brandl116aa622007-08-15 14:28:22 +000031 .. note::
32
Georg Brandl18244152009-09-02 20:34:52 +000033 Since the :func:`split` function instantiates a :class:`shlex` instance,
34 passing ``None`` for *s* will read the string to split from standard
35 input.
Georg Brandl116aa622007-08-15 14:28:22 +000036
37The :mod:`shlex` module defines the following class:
38
39
Georg Brandl18244152009-09-02 20:34:52 +000040.. class:: shlex(instream=None, infile=None, posix=False)
Georg Brandl116aa622007-08-15 14:28:22 +000041
42 A :class:`shlex` instance or subclass instance is a lexical analyzer object.
43 The initialization argument, if present, specifies where to read characters
44 from. It must be a file-/stream-like object with :meth:`read` and
Georg Brandle6bcc912008-05-12 18:05:20 +000045 :meth:`readline` methods, or a string. If no argument is given, input will
46 be taken from ``sys.stdin``. The second optional argument is a filename
Senthil Kumarana6bac952011-07-04 11:28:30 -070047 string, which sets the initial value of the :attr:`infile` attribute. If the
Georg Brandle6bcc912008-05-12 18:05:20 +000048 *instream* argument is omitted or equal to ``sys.stdin``, this second
49 argument defaults to "stdin". The *posix* argument defines the operational
50 mode: when *posix* is not true (default), the :class:`shlex` instance will
51 operate in compatibility mode. When operating in POSIX mode, :class:`shlex`
52 will try to be as close as possible to the POSIX shell parsing rules.
Georg Brandl116aa622007-08-15 14:28:22 +000053
54
55.. seealso::
56
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +000057 Module :mod:`configparser`
Georg Brandl116aa622007-08-15 14:28:22 +000058 Parser for configuration files similar to the Windows :file:`.ini` files.
59
60
61.. _shlex-objects:
62
63shlex Objects
64-------------
65
66A :class:`shlex` instance has the following methods:
67
68
69.. method:: shlex.get_token()
70
71 Return a token. If tokens have been stacked using :meth:`push_token`, pop a
72 token off the stack. Otherwise, read one from the input stream. If reading
73 encounters an immediate end-of-file, :attr:`self.eof` is returned (the empty
74 string (``''``) in non-POSIX mode, and ``None`` in POSIX mode).
75
76
77.. method:: shlex.push_token(str)
78
79 Push the argument onto the token stack.
80
81
82.. method:: shlex.read_token()
83
84 Read a raw token. Ignore the pushback stack, and do not interpret source
85 requests. (This is not ordinarily a useful entry point, and is documented here
86 only for the sake of completeness.)
87
88
89.. method:: shlex.sourcehook(filename)
90
91 When :class:`shlex` detects a source request (see :attr:`source` below) this
92 method is given the following token as argument, and expected to return a tuple
93 consisting of a filename and an open file-like object.
94
95 Normally, this method first strips any quotes off the argument. If the result
96 is an absolute pathname, or there was no previous source request in effect, or
97 the previous source was a stream (such as ``sys.stdin``), the result is left
98 alone. Otherwise, if the result is a relative pathname, the directory part of
99 the name of the file immediately before it on the source inclusion stack is
100 prepended (this behavior is like the way the C preprocessor handles ``#include
101 "file.h"``).
102
103 The result of the manipulations is treated as a filename, and returned as the
104 first component of the tuple, with :func:`open` called on it to yield the second
105 component. (Note: this is the reverse of the order of arguments in instance
106 initialization!)
107
108 This hook is exposed so that you can use it to implement directory search paths,
109 addition of file extensions, and other namespace hacks. There is no
110 corresponding 'close' hook, but a shlex instance will call the :meth:`close`
111 method of the sourced input stream when it returns EOF.
112
113 For more explicit control of source stacking, use the :meth:`push_source` and
114 :meth:`pop_source` methods.
115
116
Georg Brandl18244152009-09-02 20:34:52 +0000117.. method:: shlex.push_source(newstream, newfile=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000118
119 Push an input source stream onto the input stack. If the filename argument is
120 specified it will later be available for use in error messages. This is the
121 same method used internally by the :meth:`sourcehook` method.
122
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124.. method:: shlex.pop_source()
125
126 Pop the last-pushed input source from the input stack. This is the same method
127 used internally when the lexer reaches EOF on a stacked input stream.
128
Georg Brandl116aa622007-08-15 14:28:22 +0000129
Georg Brandl18244152009-09-02 20:34:52 +0000130.. method:: shlex.error_leader(infile=None, lineno=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132 This method generates an error message leader in the format of a Unix C compiler
133 error label; the format is ``'"%s", line %d: '``, where the ``%s`` is replaced
134 with the name of the current source file and the ``%d`` with the current input
135 line number (the optional arguments can be used to override these).
136
137 This convenience is provided to encourage :mod:`shlex` users to generate error
138 messages in the standard, parseable format understood by Emacs and other Unix
139 tools.
140
141Instances of :class:`shlex` subclasses have some public instance variables which
142either control lexical analysis or can be used for debugging:
143
144
145.. attribute:: shlex.commenters
146
147 The string of characters that are recognized as comment beginners. All
148 characters from the comment beginner to end of line are ignored. Includes just
149 ``'#'`` by default.
150
151
152.. attribute:: shlex.wordchars
153
154 The string of characters that will accumulate into multi-character tokens. By
155 default, includes all ASCII alphanumerics and underscore.
156
157
158.. attribute:: shlex.whitespace
159
160 Characters that will be considered whitespace and skipped. Whitespace bounds
161 tokens. By default, includes space, tab, linefeed and carriage-return.
162
163
164.. attribute:: shlex.escape
165
166 Characters that will be considered as escape. This will be only used in POSIX
167 mode, and includes just ``'\'`` by default.
168
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170.. attribute:: shlex.quotes
171
172 Characters that will be considered string quotes. The token accumulates until
173 the same quote is encountered again (thus, different quote types protect each
174 other as in the shell.) By default, includes ASCII single and double quotes.
175
176
177.. attribute:: shlex.escapedquotes
178
179 Characters in :attr:`quotes` that will interpret escape characters defined in
180 :attr:`escape`. This is only used in POSIX mode, and includes just ``'"'`` by
181 default.
182
Georg Brandl116aa622007-08-15 14:28:22 +0000183
184.. attribute:: shlex.whitespace_split
185
186 If ``True``, tokens will only be split in whitespaces. This is useful, for
187 example, for parsing command lines with :class:`shlex`, getting tokens in a
188 similar way to shell arguments.
189
Georg Brandl116aa622007-08-15 14:28:22 +0000190
191.. attribute:: shlex.infile
192
193 The name of the current input file, as initially set at class instantiation time
194 or stacked by later source requests. It may be useful to examine this when
195 constructing error messages.
196
197
198.. attribute:: shlex.instream
199
200 The input stream from which this :class:`shlex` instance is reading characters.
201
202
203.. attribute:: shlex.source
204
Senthil Kumarana6bac952011-07-04 11:28:30 -0700205 This attribute is ``None`` by default. If you assign a string to it, that
206 string will be recognized as a lexical-level inclusion request similar to the
Georg Brandl116aa622007-08-15 14:28:22 +0000207 ``source`` keyword in various shells. That is, the immediately following token
208 will opened as a filename and input taken from that stream until EOF, at which
209 point the :meth:`close` method of that stream will be called and the input
210 source will again become the original input stream. Source requests may be
211 stacked any number of levels deep.
212
213
214.. attribute:: shlex.debug
215
Senthil Kumarana6bac952011-07-04 11:28:30 -0700216 If this attribute is numeric and ``1`` or more, a :class:`shlex` instance will
Georg Brandl116aa622007-08-15 14:28:22 +0000217 print verbose progress output on its behavior. If you need to use this, you can
218 read the module source code to learn the details.
219
220
221.. attribute:: shlex.lineno
222
223 Source line number (count of newlines seen so far plus one).
224
225
226.. attribute:: shlex.token
227
228 The token buffer. It may be useful to examine this when catching exceptions.
229
230
231.. attribute:: shlex.eof
232
233 Token used to determine end of file. This will be set to the empty string
234 (``''``), in non-POSIX mode, and to ``None`` in POSIX mode.
235
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237.. _shlex-parsing-rules:
238
239Parsing Rules
240-------------
241
242When operating in non-POSIX mode, :class:`shlex` will try to obey to the
243following rules.
244
245* Quote characters are not recognized within words (``Do"Not"Separate`` is
246 parsed as the single word ``Do"Not"Separate``);
247
248* Escape characters are not recognized;
249
250* Enclosing characters in quotes preserve the literal value of all characters
251 within the quotes;
252
253* Closing quotes separate words (``"Do"Separate`` is parsed as ``"Do"`` and
254 ``Separate``);
255
256* If :attr:`whitespace_split` is ``False``, any character not declared to be a
257 word character, whitespace, or a quote will be returned as a single-character
258 token. If it is ``True``, :class:`shlex` will only split words in whitespaces;
259
260* EOF is signaled with an empty string (``''``);
261
262* It's not possible to parse empty strings, even if quoted.
263
264When operating in POSIX mode, :class:`shlex` will try to obey to the following
265parsing rules.
266
267* Quotes are stripped out, and do not separate words (``"Do"Not"Separate"`` is
268 parsed as the single word ``DoNotSeparate``);
269
270* Non-quoted escape characters (e.g. ``'\'``) preserve the literal value of the
271 next character that follows;
272
273* Enclosing characters in quotes which are not part of :attr:`escapedquotes`
274 (e.g. ``"'"``) preserve the literal value of all characters within the quotes;
275
276* Enclosing characters in quotes which are part of :attr:`escapedquotes` (e.g.
277 ``'"'``) preserves the literal value of all characters within the quotes, with
278 the exception of the characters mentioned in :attr:`escape`. The escape
279 characters retain its special meaning only when followed by the quote in use, or
280 the escape character itself. Otherwise the escape character will be considered a
281 normal character.
282
283* EOF is signaled with a :const:`None` value;
284
285* Quoted empty strings (``''``) are allowed;
286