2

我正在运行一个脚本,它在内部调用一个 bash 命令并相应地解析输出。例如我正在调用这个命令

result = subprocess.check_output("rg result",shell=True)
print(output)

我得到这个输出没有任何行号或任何东西

historyChecker.py:        result = subprocess.check_output("rg --help",shell=True)
historyChecker.py:        output = re.search(r'USAGE:',result)

如果我在 bash 中运行相同的命令,我会得到不同的结果

[~/history_checker/code]$ rg result                                                                                                                                               
historyChecker.py
56:        result = subprocess.check_output("rg --help",shell=True)
57:        output = re.search(r'USAGE:',result) 

知道为什么会发生这种情况以及我们如何解决这个问题。谢谢

4

1 回答 1

6

从以下文档rg

-n, <code>--line-number
显示行号(从 1 开始)。在终端中搜索时默认启用此功能。

因此,当您在终端中运行它时,会启用此选项。使用 时subprocess.check_output(),标准输出连接到管道,并且此选项未启用。

--line-number如果需要,请添加选项。

result = subprocess.check_output(["rg", "--line-number", "result"])
print(output)

您也没有做任何需要 shell 解析的事情,所以将命令行作为列表传递,不要使用shell=True.

于 2021-07-27T20:55:45.753 回答