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