python - 在没有 shell 转义序列的情况下在 Python 中打印标准输出

标签 python shell escaping sh

我正在使用 sh 在 Python 脚本中运行 git 命令。

In [1]: from sh import git

In [2]: s = git("log", "-1", pretty="format:%h %s")

In [3]: print s
4f14a66 basic debug page

这似乎按预期工作。但是,在 Django 模板中使用它会得到 [?1h= 4f14a66 basic debug page[m [K[?1l]。我尝试使用 repr() 查看此字符串中的字符,但无济于事:

In [4]: print repr(s)
4f14a66 basic debug page

事实证明,sh 中的命令返回一个具有 .stdout 属性的 RunningCommand:

In [5]: type(s)
Out[5]: sh.RunningCommand

In [7]: s.stdout
Out[7]: '\x1b[?1h\x1b=\r4f14a66 basic debug page\x1b[m\r\n\r\x1b[K\x1b[?1l\x1b>'

如何获得 "4f14a66 basic debug page" 即没有转义的字符串?从 Bash 运行命令没问题:

$ git log -1 --pretty="format:%h %s"
4f14a66 basic debug page

最佳答案

根据 this GitHub issue ,问题的正确解决方案是使用 _tty_out=False:

>>> str(git('show', format='%cN', s=True))
'\x1b[?1h\x1b=\rHonza Javorek\x1b[m\r\n\r\x1b[K\x1b[?1l\x1b>'

>>> str(git('show', format='%cN', s=True, _tty_out=False))
'Honza Javorek\n'

这也是我的重复问题的解决方案:Using sh, git show returns special characters - how to get plain output?

关于python - 在没有 shell 转义序列的情况下在 Python 中打印标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13611061/

相关文章:

regex - 多行正则表达式如何在 bash 中替换并存储在变量中?

java - super 简单的逃脱序列【初级】

windows - 带有空格和括号的批处理文件变量

java - 需要一个应用程序来修复带有未转义字符的 XML

python - 是否有一种只使用对象的模式?

Python连接列表中的数组

python - 使用\: LaTeX horizontal spacing 时 matplotlib 中的 ValueError

linux - 使用锁定文件避免脚本的两个实例同时运行时如何避免竞争条件?

linux - 如何用 sed 替换 1 个文件中的所有匹配项?

python - 如何用python做一个复杂的过滤器