python - "Unquote"/在python中解析bash参数字符串

标签 python bash escaping

我有一个 python 脚本,它从命令行参数中获取输入。例如:

./myscript.py first_item second\ item "third item"

我可以使用 pipes.quote 输出单独的项目、转义空格和特殊字符.

print " ".join(map(pipes.quote, outputItems))

是否有任何现有的“unquote”接口(interface)可以解析 bash 参数字符串,同时保持转义空格和引号字符串完整?

允许同一个 python 脚本处理这个的东西:

echo 'first_item second\ item "third item"' | ./myscript.py

最佳答案

你想要shlex.split() :

s = 'first_item second\ item "third item"'

import shlex

shlex.split(s)
Out[3]: ['first_item', 'second item', 'third item']

关于python - "Unquote"/在python中解析bash参数字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22351646/

相关文章:

linux - centos强制使用特定版本的JAVA

sqlite - 有没有办法在 sqlite 中禁用宽松的引用规则?

python - django - 使用 get_or_create 自动创建用户时设置用户权限

python - 访问类或方法时是否需要 __init__.py 中的 __all__ ?

python - 读取文件时避免使用 C 风格注释

PHP MySQL - 清理和验证建议

php - Joomla 3 - 如果类别标题包含&符号,则类别链接中断&

python - 如何让emacs自动缩进Python代码?

linux - 如何在不生成临时文件的情况下在 shell 脚本中在生成的文件前面附加行数

linux - 我可以从与要运行 diff 的容器位于同一主机上的容器运行 docker diff 吗?