我正在使用 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/