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