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