blob: 941e090c4f28088bc9ba68ddec056f30131e1a88 [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
Éric Araujo9bce3112011-07-27 18:29:31 +020037
38.. function:: quote(s)
39
40 Return a shell-escaped version of the string *s*. The returned value is a
Éric Araujo30e277b2011-07-29 15:08:42 +020041 string that can safely be used as one token in a shell command line, for
42 cases where you cannot use a list.
Éric Araujo9bce3112011-07-27 18:29:31 +020043
Éric Araujo30e277b2011-07-29 15:08:42 +020044 This idiom would be unsafe::
45
46 >>> filename = 'somefile; rm -rf ~'
47 >>> command = 'ls -l {}'.format(filename)
48 >>> print(command) # executed by a shell: boom!
49 ls -l somefile; rm -rf ~
50
51 :func:`quote` lets you plug the security hole::
52
Éric Araujo9bce3112011-07-27 18:29:31 +020053 >>> command = 'ls -l {}'.format(quote(filename))
54 >>> print(command)
Éric Araujo30e277b2011-07-29 15:08:42 +020055 ls -l 'somefile; rm -rf ~'
Éric Araujo9bce3112011-07-27 18:29:31 +020056 >>> remote_command = 'ssh home {}'.format(quote(command))
57 >>> print(remote_command)
Éric Araujo30e277b2011-07-29 15:08:42 +020058 ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"''
59
60 The quoting is compatible with UNIX shells and with :func:`split`:
61
62 >>> remote_command = split(remote_command)
63 >>> remote_command
64 ['ssh', 'home', "ls -l 'somefile; rm -rf ~'"]
65 >>> command = split(remote_command[-1])
66 >>> command
67 ['ls', '-l', 'somefile; rm -rf ~']
Éric Araujo9bce3112011-07-27 18:29:31 +020068
Eli Bendersky493846e2012-03-01 19:07:55 +020069 .. versionadded:: 3.3
Éric Araujo9bce3112011-07-27 18:29:31 +020070
Georg Brandl116aa622007-08-15 14:28:22 +000071The :mod:`shlex` module defines the following class:
72
73
Georg Brandl18244152009-09-02 20:34:52 +000074.. class:: shlex(instream=None, infile=None, posix=False)
Georg Brandl116aa622007-08-15 14:28:22 +000075
76 A :class:`shlex` instance or subclass instance is a lexical analyzer object.
77 The initialization argument, if present, specifies where to read characters
78 from. It must be a file-/stream-like object with :meth:`read` and
Georg Brandle6bcc912008-05-12 18:05:20 +000079 :meth:`readline` methods, or a string. If no argument is given, input will
80 be taken from ``sys.stdin``. The second optional argument is a filename
Senthil Kumarana6bac952011-07-04 11:28:30 -070081 string, which sets the initial value of the :attr:`infile` attribute. If the
Georg Brandle6bcc912008-05-12 18:05:20 +000082 *instream* argument is omitted or equal to ``sys.stdin``, this second
83 argument defaults to "stdin". The *posix* argument defines the operational
84 mode: when *posix* is not true (default), the :class:`shlex` instance will
85 operate in compatibility mode. When operating in POSIX mode, :class:`shlex`
86 will try to be as close as possible to the POSIX shell parsing rules.
Georg Brandl116aa622007-08-15 14:28:22 +000087
88
89.. seealso::
90
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +000091 Module :mod:`configparser`
Georg Brandl116aa622007-08-15 14:28:22 +000092 Parser for configuration files similar to the Windows :file:`.ini` files.
93
94
95.. _shlex-objects:
96
97shlex Objects
98-------------
99
100A :class:`shlex` instance has the following methods:
101
102
103.. method:: shlex.get_token()
104
105 Return a token. If tokens have been stacked using :meth:`push_token`, pop a
106 token off the stack. Otherwise, read one from the input stream. If reading
107 encounters an immediate end-of-file, :attr:`self.eof` is returned (the empty
108 string (``''``) in non-POSIX mode, and ``None`` in POSIX mode).
109
110
111.. method:: shlex.push_token(str)
112
113 Push the argument onto the token stack.
114
115
116.. method:: shlex.read_token()
117
118 Read a raw token. Ignore the pushback stack, and do not interpret source
119 requests. (This is not ordinarily a useful entry point, and is documented here
120 only for the sake of completeness.)
121
122
123.. method:: shlex.sourcehook(filename)
124
125 When :class:`shlex` detects a source request (see :attr:`source` below) this
126 method is given the following token as argument, and expected to return a tuple
127 consisting of a filename and an open file-like object.
128
129 Normally, this method first strips any quotes off the argument. If the result
130 is an absolute pathname, or there was no previous source request in effect, or
131 the previous source was a stream (such as ``sys.stdin``), the result is left
132 alone. Otherwise, if the result is a relative pathname, the directory part of
133 the name of the file immediately before it on the source inclusion stack is
134 prepended (this behavior is like the way the C preprocessor handles ``#include
135 "file.h"``).
136
137 The result of the manipulations is treated as a filename, and returned as the
138 first component of the tuple, with :func:`open` called on it to yield the second
139 component. (Note: this is the reverse of the order of arguments in instance
140 initialization!)
141
142 This hook is exposed so that you can use it to implement directory search paths,
143 addition of file extensions, and other namespace hacks. There is no
144 corresponding 'close' hook, but a shlex instance will call the :meth:`close`
145 method of the sourced input stream when it returns EOF.
146
147 For more explicit control of source stacking, use the :meth:`push_source` and
148 :meth:`pop_source` methods.
149
150
Georg Brandl18244152009-09-02 20:34:52 +0000151.. method:: shlex.push_source(newstream, newfile=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153 Push an input source stream onto the input stack. If the filename argument is
154 specified it will later be available for use in error messages. This is the
155 same method used internally by the :meth:`sourcehook` method.
156
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158.. method:: shlex.pop_source()
159
160 Pop the last-pushed input source from the input stack. This is the same method
161 used internally when the lexer reaches EOF on a stacked input stream.
162
Georg Brandl116aa622007-08-15 14:28:22 +0000163
Georg Brandl18244152009-09-02 20:34:52 +0000164.. method:: shlex.error_leader(infile=None, lineno=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000165
166 This method generates an error message leader in the format of a Unix C compiler
167 error label; the format is ``'"%s", line %d: '``, where the ``%s`` is replaced
168 with the name of the current source file and the ``%d`` with the current input
169 line number (the optional arguments can be used to override these).
170
171 This convenience is provided to encourage :mod:`shlex` users to generate error
172 messages in the standard, parseable format understood by Emacs and other Unix
173 tools.
174
175Instances of :class:`shlex` subclasses have some public instance variables which
176either control lexical analysis or can be used for debugging:
177
178
179.. attribute:: shlex.commenters
180
181 The string of characters that are recognized as comment beginners. All
182 characters from the comment beginner to end of line are ignored. Includes just
183 ``'#'`` by default.
184
185
186.. attribute:: shlex.wordchars
187
188 The string of characters that will accumulate into multi-character tokens. By
189 default, includes all ASCII alphanumerics and underscore.
190
191
192.. attribute:: shlex.whitespace
193
194 Characters that will be considered whitespace and skipped. Whitespace bounds
195 tokens. By default, includes space, tab, linefeed and carriage-return.
196
197
198.. attribute:: shlex.escape
199
200 Characters that will be considered as escape. This will be only used in POSIX
201 mode, and includes just ``'\'`` by default.
202
Georg Brandl116aa622007-08-15 14:28:22 +0000203
204.. attribute:: shlex.quotes
205
206 Characters that will be considered string quotes. The token accumulates until
207 the same quote is encountered again (thus, different quote types protect each
208 other as in the shell.) By default, includes ASCII single and double quotes.
209
210
211.. attribute:: shlex.escapedquotes
212
213 Characters in :attr:`quotes` that will interpret escape characters defined in
214 :attr:`escape`. This is only used in POSIX mode, and includes just ``'"'`` by
215 default.
216
Georg Brandl116aa622007-08-15 14:28:22 +0000217
218.. attribute:: shlex.whitespace_split
219
220 If ``True``, tokens will only be split in whitespaces. This is useful, for
221 example, for parsing command lines with :class:`shlex`, getting tokens in a
222 similar way to shell arguments.
223
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225.. attribute:: shlex.infile
226
227 The name of the current input file, as initially set at class instantiation time
228 or stacked by later source requests. It may be useful to examine this when
229 constructing error messages.
230
231
232.. attribute:: shlex.instream
233
234 The input stream from which this :class:`shlex` instance is reading characters.
235
236
237.. attribute:: shlex.source
238
Senthil Kumarana6bac952011-07-04 11:28:30 -0700239 This attribute is ``None`` by default. If you assign a string to it, that
240 string will be recognized as a lexical-level inclusion request similar to the
Georg Brandl116aa622007-08-15 14:28:22 +0000241 ``source`` keyword in various shells. That is, the immediately following token
242 will opened as a filename and input taken from that stream until EOF, at which
243 point the :meth:`close` method of that stream will be called and the input
244 source will again become the original input stream. Source requests may be
245 stacked any number of levels deep.
246
247
248.. attribute:: shlex.debug
249
Senthil Kumarana6bac952011-07-04 11:28:30 -0700250 If this attribute is numeric and ``1`` or more, a :class:`shlex` instance will
Georg Brandl116aa622007-08-15 14:28:22 +0000251 print verbose progress output on its behavior. If you need to use this, you can
252 read the module source code to learn the details.
253
254
255.. attribute:: shlex.lineno
256
257 Source line number (count of newlines seen so far plus one).
258
259
260.. attribute:: shlex.token
261
262 The token buffer. It may be useful to examine this when catching exceptions.
263
264
265.. attribute:: shlex.eof
266
267 Token used to determine end of file. This will be set to the empty string
268 (``''``), in non-POSIX mode, and to ``None`` in POSIX mode.
269
Georg Brandl116aa622007-08-15 14:28:22 +0000270
271.. _shlex-parsing-rules:
272
273Parsing Rules
274-------------
275
276When operating in non-POSIX mode, :class:`shlex` will try to obey to the
277following rules.
278
279* Quote characters are not recognized within words (``Do"Not"Separate`` is
280 parsed as the single word ``Do"Not"Separate``);
281
282* Escape characters are not recognized;
283
284* Enclosing characters in quotes preserve the literal value of all characters
285 within the quotes;
286
287* Closing quotes separate words (``"Do"Separate`` is parsed as ``"Do"`` and
288 ``Separate``);
289
290* If :attr:`whitespace_split` is ``False``, any character not declared to be a
291 word character, whitespace, or a quote will be returned as a single-character
292 token. If it is ``True``, :class:`shlex` will only split words in whitespaces;
293
294* EOF is signaled with an empty string (``''``);
295
296* It's not possible to parse empty strings, even if quoted.
297
298When operating in POSIX mode, :class:`shlex` will try to obey to the following
299parsing rules.
300
301* Quotes are stripped out, and do not separate words (``"Do"Not"Separate"`` is
302 parsed as the single word ``DoNotSeparate``);
303
304* Non-quoted escape characters (e.g. ``'\'``) preserve the literal value of the
305 next character that follows;
306
307* Enclosing characters in quotes which are not part of :attr:`escapedquotes`
308 (e.g. ``"'"``) preserve the literal value of all characters within the quotes;
309
310* Enclosing characters in quotes which are part of :attr:`escapedquotes` (e.g.
311 ``'"'``) preserves the literal value of all characters within the quotes, with
312 the exception of the characters mentioned in :attr:`escape`. The escape
313 characters retain its special meaning only when followed by the quote in use, or
314 the escape character itself. Otherwise the escape character will be considered a
315 normal character.
316
317* EOF is signaled with a :const:`None` value;
318
Éric Araujo9bce3112011-07-27 18:29:31 +0200319* Quoted empty strings (``''``) are allowed.