简体   繁体   English

为什么 python 子进程运行的 ripgrep 结果与 shell 中的 rg 运行不同

[英]Why ripgrep results from python subprocess run differ from rg run in the shell

If I run rg in bash directly, the output information includes the found file names (on a separate line), and then on a separate line for each match the line number and content for that match:如果我直接在 bash 中运行rg ,则 output 信息包括找到的文件名(在单独的行上),然后在每个匹配的单独行上包含该匹配的行号和内容:

11:38 (main *+) durl $ rg format
durl/__main__.py
35:            print(util.format_output(repo.url, line))
38:            print(util.format_output(repo.url, line, linenumber=n))

durl/util.py
15:def format_output(prefix, filename: str, linenumber: str=None) -> str:

But if I run the same command from python subprocess run, the displayed information of the matched results includes the filename on each line and do not include a line number.但是如果我从 python subprocess进程运行中运行相同的命令,则匹配结果的显示信息包括每行的文件名,包括行号。 Why is that so?为什么呢? (I am running on MacOS) (我在 MacOS 上运行)

11:38 (main *+) durl $ ipython
Python 3.9.5 (default, May  4 2021, 03:36:27)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.27.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import subprocess

In [2]: p = subprocess.run('rg format', text=True, shell=True, capture_output=True,)

In [3]: p.stdout
Out[3]: 'durl/__main__.py:            print(util.format_output(repo.url, line))\ndurl/__main__.py:            print(util.format_output(repo.url, line, linenumber=n))\ndurl/util.py:def format_output(prefix, filename: str, linenumber: str=None) -> str:\n'

In [4]: p.stdout.split('\n')
Out[4]:
['durl/__main__.py:            print(util.format_output(repo.url, line))',
 'durl/__main__.py:            print(util.format_output(repo.url, line, linenumber=n))',
 'durl/util.py:def format_output(prefix, filename: str, linenumber: str=None) -> str:',
 '']

Because ripgrep detects if an interactive tty exists on stdout, and if so, changes the output format to be more "friendly."因为 ripgrep 会检测 stdout 上是否存在交互式 tty,如果存在,则将 output 格式更改为更“友好”。 It's the same thing that ls does for example.例如,这与ls所做的相同。

They are the same.他们是一样的。 In your example, you are looking at how Python represents the string, but if you actually print it, you'll see that it's exactly the same.在您的示例中,您正在查看 Python 如何表示字符串,但如果您实际print它,您会发现它完全相同。

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

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