简体   繁体   English

在没有 shell 转义序列的 Python 中打印标准输出

[英]Print stdout in Python without shell escape sequences

I'm using sh to run git commands inside a Python script.我正在使用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

This seems to work as expected.这似乎按预期工作。 However, using this in a Django template gives [?1h= 4f14a66 basic debug page[m [K[?1l> .但是,在 Django 模板中使用它会给出[?1h= 4f14a66 basic debug page[m [K[?1l> I tried to see what characters were in this string using repr() , to no avail:我尝试使用repr()查看此字符串中的字符,但无济于事:

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

It turns out commands in sh return a RunningCommand that has a .stdout attribute:事实证明,在命令sh回报RunningCommand具有.stdout属性:

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>'

How do I get "4f14a66 basic debug page" ie the string without the escapes?如何获得"4f14a66 basic debug page"即没有转义的字符串? Running the command from Bash is fine:从 Bash 运行命令很好:

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

According to this GitHub issue , correct solution to the problem is to use _tty_out=False :根据 这个 GitHub 问题问题的正确解决方案是使用_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'

This is also solution for my duplicate question: Using sh, git show returns special characters - how to get plain output?这也是我重复问题的解决方案: 使用 sh,git show 返回特殊字符 - 如何获得纯输出?

s.stdout in the REPL will not print it but display its repr() . REPL 中的s.stdout不会打印它,而是显示它的repr() Use print s.stdout to get what you are looking for.使用print s.stdout获取您要查找的内容。

If you do not want any escape codes consider executing it using subprocess.call() - with stdout not being a tty most programs do not output any escape sequences.如果您不想要任何转义码,请考虑使用subprocess.call()执行它 - stdout 不是 tty 大多数程序不输出任何转义序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM