如何在python中格式化git show的输出

2024-05-13 18:31:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python操作git show的输出

我使用follow获得git show的输出

sh.git.show('b24f6f825324fb939210077c02a8944b59399510')
out.stdout

但问题出在一行

b'\x1b[33mcommit b24f6f825324fb939210077c02a8944b59399510\x1b[m\nAuthor: Nuno Lopes <nlopess@php.net>\nDate:   Sun Jul 6 15:23:44 2008 +0000\n\n    MFB: fix CVE-2008-2371\n\n\x1b[1mdiff --git a/ext/pcre/pcrelib/pcre_compile.c b/ext/pcre/pcrelib/pcre_compile.c\x1b[m\n\x1b[1mindex 51a51e1253..0f3ebf93fd 100644\x1b[m\n\x1b[1m--- a/ext/pcre/pcrelib/pcre_compile.c\x1b[m\n\x1b[1m+++ b/ext/pcre/pcrelib/pcre_compile.c\x1b[m\n\x1b[36m@@ -4929,7 +4929,7 @@\x1b[m \x1b[mwe set the flag only if there is a literal "\\r" or "\\n" in the class. */\x1b[m\n                (lengthptr == NULL || *lengthptr == 2 + 2*LINK_SIZE))\x1b[m\n             {\x1b[m\n             cd->external_options = newoptions;\x1b[m\n\x1b[31m-            options = newoptions;\x1b[m\n\x1b[32m+\x1b[m\x1b[32m            options = *optionsptr = newoptions;\x1b[m\n             }\x1b[m\n          else\x1b[m\n             {\x1b[m\n'

那么,有什么方法可以像shell中的命令输出一样获得格式输出呢。这样我就可以得到我想要的任何线路

commit b24f6f825324fb939210077c02a8944b59399510
Author: Nuno Lopes <nlopess@php.net>
Date:   Sun Jul 6 15:23:44 2008 +0000

    MFB: fix CVE-2008-2371

diff --git a/ext/pcre/pcrelib/pcre_compile.c b/ext/pcre/pcrelib/pcre_compile.c
index 51a51e1253..0f3ebf93fd 100644
--- a/ext/pcre/pcrelib/pcre_compile.c
+++ b/ext/pcre/pcrelib/pcre_compile.c
@@ -4929,7 +4929,7 @@ we set the flag only if there is a literal "\r" or "\n" in the class. */
                (lengthptr == NULL || *lengthptr == 2 + 2*LINK_SIZE))
             {
             cd->external_options = newoptions;
-            options = newoptions;
+            options = *optionsptr = newoptions;
             }
          else
             {

Tags: thegitshowextoptionspcrecompilex1b
2条回答

除了@greenmaveguy的答案外,您还可以使用 format=<format>标志自定义从git show命令返回的内容的格式。见here

您在输出中看到的垃圾文本:

\x1b[33m

似乎是console color escape codes。换句话说,git使用什么来为文本着色

如果您不希望在输出中包含这些控制台代码,那么您可以告诉git不要以彩色打印命令结果According to the documentation, the ^{} or ^{} flags will accomplish this,因此相应的sh.git命令应该是:

sh.git.show('b24f6f825324fb939210077c02a8944b59399510', color='never')

请注意,输出仍然是bytestring,当然,\n和其他“正常”控制字符仍将出现在该输出中(您真的不希望换行符消失,是吗?)。可以使用bytes.decode()将bytestring转换为常规字符串,如果使用print()输出字符串,则应正确处理控制字符

(如果您只是print()更改了您正在执行的操作的结果,我甚至希望颜色能够正常工作,但是如果您打算对输出执行其他操作,那么您可能不希望颜色转义码混淆输出)

相关问题 更多 >