模块 shlex
模块 shlex 提供了 shell 转义相关的功能
shlex.quote(s: str) -> str
返回 s 经过 shell 转义的字符串 。
返回的字符串可以安全地用作 shell 命令行中的词法单元。
filename = 'somefile; rm -rf ~'
command = 'ls -l {}'.format(shlex.quote(filename))
assert(command == "ls -l 'somefile; rm -rf ~'")
remote_command = 'ssh home {}'.format(shlex.quote(command))
assert(remote_command == "ssh home 'ls -l '\"'\"'somefile; rm -rf ~'\"'\"''")
shlex.split(s: str) -> [str]
用 shell 的语法拆分字符串 s。
assert(shlex.split("echo -n 'Multiple words'") == ['echo', '-n', 'Multiple words'])
shlex.join(split_command: [str]) -> str
将列表 split_command 中的词法单元用 shell 语法串联起来,返回一个字符串。本函数是 .split 的逆运算。
assert(shlex.join(['echo', '-n', 'Multiple words']), "echo -n 'Multiple words'")