2

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:

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. Why is that so? (I am running on 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:',
 '']
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
nos
  • 19,875
  • 27
  • 98
  • 134
  • Try `rg format | cat` in your shell and compare to `rg format` alone. – Charles Duffy Dec 29 '21 at 19:14
  • (Also, please don't make it readers' problems to try to figure out what the specific difference you're asking about is; it's not as visually obvious as you may think that the filenames are only reproduced on each line in the stdout-to-a-FIFO case; I had to reread several times to catch it, and one answerer apparently missed it entirely -- have now edited to be more explicit). – Charles Duffy Dec 29 '21 at 19:15
  • BTW, if you dropped the `capture_output=True`, you'd have the same behavior for both (because `rg` would inherit stdout from Python and thus see that output was going to a TTY, and thus optimize for human-friendly behavior as opposed to machine-friendly behavior). – Charles Duffy Dec 29 '21 at 19:20

1 Answers1

1

Because ripgrep detects if an interactive tty exists on stdout, and if so, changes the output format to be more "friendly." It's the same thing that ls does for example.

BurntSushi5
  • 13,917
  • 7
  • 52
  • 45