在Python中打印stdout,没有shell转义序列 [英] Print stdout in Python without shell escape sequences

查看:146
本文介绍了在Python中打印stdout,没有shell转义序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using sh to run git commands inside a Python script.

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基本调试页面[m [K [?1l> 。我尝试使用 repr()查看此字符串中的字符,无效:

This seems to work as expected. However, using this in a Django template gives [?1h= 4f14a66 basic debug page[m [K[?1l>. I tried to see what characters were in this string using repr(), to no avail:

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

结果是 sh 中的命令返回一个$ code> RunningCommand ,它有一个 .stdout 属性:

It turns out commands in sh return a RunningCommand that has a .stdout attribute:

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基本调试页面即没有转义的字符串?从Bash运行命令是很好的:

How do I get "4f14a66 basic debug page" i.e. the string without the escapes? Running the command from Bash is fine:

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


推荐答案

<$ c $ REPL中的c> s.stdout 不会打印它,而是显示它的 repr()。使用 print s.stdout 来获取您要查找的内容。

s.stdout in the REPL will not print it but display its repr(). Use print s.stdout to get what you are looking for.

如果您不想使用任何转义代码执行它使用 subprocess.call() - stdout不是tty大多数程序不输出任何转义序列。

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.

这篇关于在Python中打印stdout,没有shell转义序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆