【问题标题】:python different output when run on bash and subprocess在bash和子进程上运行时python不同的输出
【发布时间】:2021-10-03 16:07:16
【问题描述】:

我正在运行一个脚本,该脚本在内部调用一个 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) 

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

【问题讨论】:

  • 所以基本上你在问为什么一个“终端”的格式与另一个不同?
  • 有些程序会根据标准输出是否为终端来改变其输出格式。

标签: python bash format subprocess ripgrep


【解决方案1】:

来自rg的文档:

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

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

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

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

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

【讨论】:

  • 或者,使用-p aka --pretty 获得与rg 默认打印到终端的相同输出。
  • @thatotherguy 虽然可能不需要颜色。
猜你喜欢
  • 1970-01-01
  • 2011-05-23
  • 1970-01-01
  • 1970-01-01
  • 2012-10-04
  • 2015-10-07
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
相关资源
最近更新 更多