気付く前にshlex.split
、私は次のことをしました。
import sys
_WORD_DIVIDERS = set((' ', '\t', '\r', '\n'))
_QUOTE_CHARS_DICT = {
'\\': '\\',
' ': ' ',
'"': '"',
'r': '\r',
'n': '\n',
't': '\t',
}
def _raise_type_error():
raise TypeError("Bytes must be decoded to Unicode first")
def parse_to_argv_gen(instring):
is_in_quotes = False
instring_iter = iter(instring)
join_string = instring[0:0]
c_list = []
c = ' '
while True:
# Skip whitespace
try:
while True:
if not isinstance(c, str) and sys.version_info[0] >= 3:
_raise_type_error()
if c not in _WORD_DIVIDERS:
break
c = next(instring_iter)
except StopIteration:
break
# Read word
try:
while True:
if not isinstance(c, str) and sys.version_info[0] >= 3:
_raise_type_error()
if not is_in_quotes and c in _WORD_DIVIDERS:
break
if c == '"':
is_in_quotes = not is_in_quotes
c = None
elif c == '\\':
c = next(instring_iter)
c = _QUOTE_CHARS_DICT.get(c)
if c is not None:
c_list.append(c)
c = next(instring_iter)
yield join_string.join(c_list)
c_list = []
except StopIteration:
yield join_string.join(c_list)
break
def parse_to_argv(instring):
return list(parse_to_argv_gen(instring))
これはPython2.xおよび3.xで機能します。Python 2.xでは、バイト文字列とUnicode文字列を直接処理します。Python 3.xでは、[Unicode]文字列のみbytes
を受け入れ、オブジェクトは受け入れません。
これは、シェルargv分割とまったく同じように動作するわけではありません。また、CR、LF、およびTAB文字を、として引用符で囲み、実際のCR、LF、TABに変換することもできます(\r
これは行いません)。ですから、自分の関数を書くことは私のニーズに役立ちました。プレーンシェルスタイルのargv分割が必要な場合は、より良いと思います。少し違うことをするためのベースラインとして役立つ場合に備えて、このコードを共有しています。\n
\t
shlex.split
shlex.split