shlex
— Простой лексический анализ¶
New in version 1.5.2.
Source code: :source:`Lib/shlex.py`
Класс shlex
упрощает написание лексических анализаторов для
простых синтаксисов, похожих на Unix shell. Это часто полезно для мини
языков (например, для запуска управляющих файлов для приложений Python), или
для парсинга строк.
Вплоть до 2.7.3 этот модуль не поддерживал ввод Unicode.
Модуль shlex
определяет следующую функцию:
-
shlex.
split
(s[, comments[, posix]])[source]¶ Разделяет строку s при помощи shell-подобного синтаксиса. Если comments равен
False
(по умолчанию), парсинг комментариев в данной строке будет отключён (установка атрибутаcommenters
экземпляраshlex
в пустую строку). Эта функция по умолчанию работает в режиме POSIX, но использует не-POSIX режим, если аргумент posix ложный.New in version 2.3.
Changed in version 2.6: Добавлен параметр posix.
Модуль shlex
определяет следующий класс:
-
class
shlex.
shlex
([instream[, infile[, posix]]])[source]¶ Экземпляр
shlex
или экземпляр его подкласса является объектом лексического анализатора. Первый аргумент, если есть, определяет откуда должны считываться данные. Это должен быть файл- или потоко-подобный объект, с методамиread()
иreadline()
, или строкой (строки можно использовать начиная с Python 2.3). Если аругменты не указаны, ввод будет получен изsys.stdin
. Второй не обязательный аргумент является строкой с именем файла, который задаёт начальное значение для атрибутаinfile
. Если аргумент instream опущен или равенsys.stdin
, второй аргумент по умолчанию равен “stdin”. Аргумент posix был представлен в Python 2.3, и определяет режим работы. Когда posix не истина (по умолчанию), экземплярshlex
будет работать в режиме совместимости. Когда он работает в режиме POSIX,shlex
будет пытаться работать как можно ближе к правилам парсинга POSIX shell`a.
See also
- Модуль
ConfigParser
- Парсер для конфигурационных файлов, похожих на Windows файлы
.ini
.
Объекты shlex¶
Экземпляры shlex
имеют следующие методы:
-
shlex.
get_token
()[source]¶ Возвращает токен. Если токен был помещён в стек при помощи
push_token()
, то выталкивает его из стека. В противном случае, считывает его из потока ввода. Если при чтении сразу возникает конец файла, то возвращаетсяeof
(пустая строка (''
) в режиме не-POSIX, иNone
в режиме POSIX).
-
shlex.
read_token
()[source]¶ Считывает сырой токен. Игнорирует pushback stack, и не интерпретирует источник запроса. (Обычно это не используемая точка входа и приведена тут только для полноты картины.)
-
shlex.
sourcehook
(filename)[source]¶ Когда
shlex
определяет исходный запрос (смsource
ниже), этот метод получает следующий токен в качестве аргумента и возвращает кортеж, содержащий имя файла и открытый файлоподобный объект (this method is given the following token as argument, and expected to return a tuple consisting of a filename and an open file-like object).Обычно этот метод отрезает все кавычки аргумента. Если в результате получается абсолютный путь Normally, this method first strips any quotes off the argument. If the result is an absolute pathname, or there was no previous source request in effect, or the previous source was a stream (such as
sys.stdin
), the result is left alone. Otherwise, if the result is a relative pathname, the directory part of the name of the file immediately before it on the source inclusion stack is prepended (this behavior is like the way the C preprocessor handles#include "file.h"
).The result of the manipulations is treated as a filename, and returned as the first component of the tuple, with
open()
called on it to yield the second component. (Note: this is the reverse of the order of arguments in instance initialization!)This hook is exposed so that you can use it to implement directory search paths, addition of file extensions, and other namespace hacks. There is no corresponding ‘close’ hook, but a shlex instance will call the
close()
method of the sourced input stream when it returns EOF.For more explicit control of source stacking, use the
push_source()
andpop_source()
methods.
-
shlex.
push_source
(stream[, filename])[source]¶ Push an input source stream onto the input stack. If the filename argument is specified it will later be available for use in error messages. This is the same method used internally by the
sourcehook()
method.New in version 2.1.
-
shlex.
pop_source
()[source]¶ Pop the last-pushed input source from the input stack. This is the same method used internally when the lexer reaches EOF on a stacked input stream.
New in version 2.1.
-
shlex.
error_leader
([file[, line]])[source]¶ This method generates an error message leader in the format of a Unix C compiler error label; the format is
'"%s", line %d: '
, where the%s
is replaced with the name of the current source file and the%d
with the current input line number (the optional arguments can be used to override these).This convenience is provided to encourage
shlex
users to generate error messages in the standard, parseable format understood by Emacs and other Unix tools.
Instances of shlex
subclasses have some public instance
variables which either control lexical analysis or can be used for debugging:
-
shlex.
commenters
¶ The string of characters that are recognized as comment beginners. All characters from the comment beginner to end of line are ignored. Includes just
'#'
by default.
-
shlex.
wordchars
¶ The string of characters that will accumulate into multi-character tokens. By default, includes all ASCII alphanumerics and underscore.
-
shlex.
whitespace
¶ Characters that will be considered whitespace and skipped. Whitespace bounds tokens. By default, includes space, tab, linefeed and carriage-return.
-
shlex.
escape
¶ Characters that will be considered as escape. This will be only used in POSIX mode, and includes just
'\'
by default.New in version 2.3.
-
shlex.
quotes
¶ Characters that will be considered string quotes. The token accumulates until the same quote is encountered again (thus, different quote types protect each other as in the shell.) By default, includes ASCII single and double quotes.
-
shlex.
escapedquotes
¶ Characters in
quotes
that will interpret escape characters defined inescape
. This is only used in POSIX mode, and includes just'"'
by default.New in version 2.3.
-
shlex.
whitespace_split
¶ If
True
, tokens will only be split in whitespaces. This is useful, for example, for parsing command lines withshlex
, getting tokens in a similar way to shell arguments.New in version 2.3.
-
shlex.
infile
¶ The name of the current input file, as initially set at class instantiation time or stacked by later source requests. It may be useful to examine this when constructing error messages.
-
shlex.
source
¶ This attribute is
None
by default. If you assign a string to it, that string will be recognized as a lexical-level inclusion request similar to thesource
keyword in various shells. That is, the immediately following token will opened as a filename and input taken from that stream until EOF, at which point theclose()
method of that stream will be called and the input source will again become the original input stream. Source requests may be stacked any number of levels deep.
-
shlex.
debug
¶ If this attribute is numeric and
1
or more, ashlex
instance will print verbose progress output on its behavior. If you need to use this, you can read the module source code to learn the details.
-
shlex.
lineno
¶ Source line number (count of newlines seen so far plus one).
-
shlex.
token
¶ The token buffer. It may be useful to examine this when catching exceptions.
-
shlex.
eof
¶ Token used to determine end of file. This will be set to the empty string (
''
), in non-POSIX mode, and toNone
in POSIX mode.New in version 2.3.
Parsing Rules¶
When operating in non-POSIX mode, shlex
will try to obey to the
following rules.
- Quote characters are not recognized within words (
Do"Not"Separate
is parsed as the single wordDo"Not"Separate
); - Escape characters are not recognized;
- Enclosing characters in quotes preserve the literal value of all characters within the quotes;
- Closing quotes separate words (
"Do"Separate
is parsed as"Do"
andSeparate
); - If
whitespace_split
isFalse
, any character not declared to be a word character, whitespace, or a quote will be returned as a single-character token. If it isTrue
,shlex
will only split words in whitespaces; - EOF is signaled with an empty string (
''
); - It’s not possible to parse empty strings, even if quoted.
When operating in POSIX mode, shlex
will try to obey to the
following parsing rules.
- Quotes are stripped out, and do not separate words (
"Do"Not"Separate"
is parsed as the single wordDoNotSeparate
); - Non-quoted escape characters (e.g.
'\'
) preserve the literal value of the next character that follows; - Enclosing characters in quotes which are not part of
escapedquotes
(e.g."'"
) preserve the literal value of all characters within the quotes; - Enclosing characters in quotes which are part of
escapedquotes
(e.g.'"'
) preserves the literal value of all characters within the quotes, with the exception of the characters mentioned inescape
. The escape characters retain its special meaning only when followed by the quote in use, or the escape character itself. Otherwise the escape character will be considered a normal character. - EOF is signaled with a
None
value; - Quoted empty strings (
''
) are allowed;