Python shlex 实战:分词、引用与参数往返,不把文本当命令执行

10-23 6阅读

配置文件里的一行参数,常常同时包含空格、引号和空字符串。直接用字符串的 split 方法拆开,会破坏原本属于同一参数的内容。shlex 适合处理类 Unix shell 的简单文本语法,但它只做词法处理:分词、加引用都不是执行,更不是隔离不可信程序的沙箱。

Python shlex 实战:分词、引用与参数往返,不把文本当命令执行
AI 模型生成的概念示意图:文本被分成参数块,不代表执行命令;非软件截图。

下面五段程序均可单独保存运行,只导入标准库,不读取文件、不访问网络,也不启动外部命令。每个 require 检查失败都会显式抛出异常,不会像 assert 那样被优化模式移除。实测环境为 Python 3.12.14 与 3.13.5,两者的普通模式和 -O 模式均核对了完整标准输出。

一、空白分隔不等于丢掉空参数

默认 split 使用 POSIX 模式,空格、制表符与换行可以划分参数;引号会被去掉,却保留内部空格。没有内容的输入得到空列表,成对引号则代表一个空参数,这两种结果不能混用。相邻的引号片段还能合成一个参数,而非自动插入分隔符。官方解析规则说明了这些边界。

独立程序:

import shlex


def require(ok, label):
    if not ok:
        raise RuntimeError(label)


require(shlex.split("") == [], "empty input")
require(shlex.split(" \t\n\r ") == [], "only whitespace")
require(shlex.split("one\ttwo\nthree") == ["one", "two", "three"], "boundaries")
require(shlex.split("''") == [""], "empty single quotes")
require(shlex.split('""') == [""], "empty double quotes")
require(shlex.split("one '' two") == ["one", "", "two"], "empty argument")
require(shlex.split('"two words"') == ["two words"], "quoted space")
require(shlex.split(r"two\ words") == ["two words"], "escaped space")
require(shlex.split('a"b c"d') == ["ab cd"], "adjacent fragments")
print(shlex.split('  pack  "two words"  ""  '))
print("whitespace checks: 9")

预期标准输出:

['pack', 'two words', '']
whitespace checks: 9

二、往返保留参数,不保留原始排版

quote 面向一个参数,join 面向参数序列。参数中的撇号不必自行拼接转义,交给库处理后,再用默认 split 验证是否还原即可。真正应比较的是参数列表相等,而不是原始字符串相等。join 会重新组织分隔与引号,多余空格、原先选用的单双引号不会原样保存。需要保存用户输入时,应另存原文。官方函数说明给出了对应关系。

独立程序:

import shlex


def require(ok, label):
    if not ok:
        raise RuntimeError(label)


argv = ["pack", "two words", "", "O'Reilly", "$HOME"]
text = shlex.join(argv)
require(shlex.quote("simple.txt") == "simple.txt", "plain token")
require(shlex.quote("") == "''", "quote empty")
require(shlex.quote("a b") == "'a b'", "quote space")
require(shlex.split(shlex.quote("O'Reilly")) == ["O'Reilly"], "apostrophe")
require(shlex.split(text) == argv, "roundtrip argv")
require(shlex.join([]) == "", "join empty list")
require(shlex.split(shlex.join([""])) == [""], "one empty token")
require(shlex.join(["tool", "a b", ""]) == "tool 'a b' ''", "joined form")
original = '  pack   "two words"  '
require(shlex.join(shlex.split(original)) == "pack 'two words'", "normal form")
require(shlex.join(shlex.split(original)) != original, "not original layout")
print(shlex.split(text))
print(shlex.join(shlex.split(original)))
print("roundtrip checks: 10")

预期标准输出:

['pack', 'two words', '', "O'Reilly", '$HOME']
pack 'two words'
roundtrip checks: 10

三、注释开关必须写进格式约定

split 默认 comments=False,因此井号通常是数据;启用注释后,从未受引号或转义保护的井号到行末会被忽略。不要把这个开关当成无害的清理步骤,它会改变参数本身。尤其注意紧贴文字的井号也能开启注释,这里不等同于完整 shell 的注释规则。解析标签、片段标识等内容时,应先确定输入格式是否真的允许注释。注释属性说明可用于核对。

独立程序:

import shlex


def require(ok, label):
    if not ok:
        raise RuntimeError(label)


text = "tool alpha # note\nbeta"
keep = shlex.split(text, comments=False)
drop = shlex.split(text, comments=True)
require(keep == ["tool", "alpha", "#", "note", "beta"], "keep comments")
require(drop == ["tool", "alpha", "beta"], "drop to newline")
require(shlex.split(text) == keep, "default false")
require(shlex.split("a#b", comments=False) == ["a#b"], "literal hash")
require(shlex.split("a#b", comments=True) == ["a"], "attached comment")
require(shlex.split("'#tag'", comments=True) == ["#tag"], "quoted hash")
require(shlex.split(r"\#tag", comments=True) == ["#tag"], "escaped hash")
require(shlex.split("# only", comments=True) == [], "comment only")
print(keep)
print(drop)
print("comment checks: 8")

预期标准输出:

['tool', 'alpha', '#', 'note', 'beta']
['tool', 'alpha', 'beta']
comment checks: 8

四、拒绝残缺输入,不偷偷修补

引号未闭合,或反斜杠后缺少待转义字符,都会使这些示例抛出 ValueError。不要遇错便补一个引号继续处理,否则可能改变用户本意。程序只比较异常类型,不依赖错误消息的具体文字。这里也验证 None 在两个测试版本中抛出 ValueError;官方记录自 3.12 起它不再转为读取标准输入。双引号中的反斜杠并非总会消失,单引号内则保留其字面值。

独立程序:

import shlex


def require(ok, label):
    if not ok:
        raise RuntimeError(label)


def error_kind(text):
    try:
        shlex.split(text)
    except (ValueError, TypeError) as exc:
        return type(exc).__name__
    return "no error"


require(error_kind("'unfinished") == "ValueError", "single quote")
require(error_kind('"unfinished') == "ValueError", "double quote")
require(error_kind("word" + "\\") == "ValueError", "trailing escape")
require(error_kind('"word' + "\\") == "ValueError", "escape in quote")
require(error_kind(None) == "ValueError", "None since 3.12")
require(error_kind("word") == "no error", "ordinary text")
require(shlex.split(r"word\\") == ["word\\"], "paired escapes")
require(shlex.split(r"'a\b'") == [r"a\b"], "single quote literal")
require(shlex.split(r'"a\q"') == [r"a\q"], "double quote ordinary escape")
require(shlex.split(r'"a\"b"') == ['a"b'], "escaped double quote")
print(error_kind("'unfinished"))
print(error_kind("word" + "\\"))
print(error_kind(None))
print("error checks: 10")

预期标准输出:

ValueError
ValueError
ValueError
error checks: 10

五、元字符留在列表里,不代表发生了操作

下面的美元符号、星号、管道、分号与重定向符都只是测试数据。split 不展开变量、不匹配文件、不建立管道,也不执行命令替换;紧贴文字的竖线仍可能留在同一个词里。真实 shell 对这些语法的解释属于另一层,不能把分词结果冒充 shell 的执行结果。

若业务确实要启动一个可信程序,优先设计为原始参数列表配合 shell=False,而不是拼出字符串再交给 shell。列表元素不应预先套 quote,否则引号可能成为参数内容。末例仅构造调用计划,绝不调用 subprocess。示意中的双连字符也只有在目标程序支持时才表示选项结束;仍需限制可执行文件、选项和访问范围。官方安全说明解释了这一层差异。

独立程序:

import shlex


def require(ok, label):
    if not ok:
        raise RuntimeError(label)


text = "reader $HOME *.txt a|b a;b > out"
tokens = shlex.split(text)
require(tokens[1] == "$HOME", "no variable expansion")
require(tokens[2] == "*.txt", "no glob expansion")
require(tokens[3] == "a|b", "no pipeline")
require(tokens[4] == "a;b", "no command separator")
require(tokens[5:] == [">", "out"], "no redirection")
require(shlex.split("a | b") == ["a", "|", "b"], "spaced punctuation")
require(shlex.split("$(date)") == ["$(date)"], "no command substitution")
argv = ["reader", "--", "two words;notice.txt"]
plan = {"args": argv, "shell": False}
require(plan["args"][2] == "two words;notice.txt", "raw single argument")
require(plan["shell"] is False, "planned shell false")
require(shlex.split(shlex.join(argv)) == argv, "display roundtrip")
print(tokens)
print(plan)
print("No process was started.")
print("literal checks: 10")

预期标准输出:

['reader', '$HOME', '*.txt', 'a|b', 'a;b', '>', 'out']
{'args': ['reader', '--', 'two words;notice.txt'], 'shell': False}
No process was started.
literal checks: 10

使用前最后确认

以上规则针对 POSIX 风格文本,不是 Windows cmd 或 PowerShell 的引用方案,参见官方警告。把 posix 关掉也不会得到通用的 Windows 解析器。Windows 批处理文件另有系统 shell 介入的特殊情况,不能套用这里的列表示意来保证安全。解析成功只证明文本符合所选词法规则,不证明目标程序或参数安全。

本文共含四十七项显式检查,四组环境组合的二十次独立运行全部通过。官方在线文档会随维护版本更新,实测版本以本文列出的解释器为准。异常行为还对照了 CPython 3.12.14 源码与 3.13.5 源码,不把测试结论扩大为所有平台的执行保证。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。