Reputation: 5167
I'm putting together a teaching project in which students will reimplement the grep utility in python. One feature I wanted to implement grep's ability to output matching text in color. To do this, I used ANSI escape sequences:
# min_example.py
START = '\033[91m'
END = '\033[0m'
some_line = f'this is {START}matching{END} text'
print(some_line)
It works exactly as expected. However, when piping the output to a text file, the raw escape sequences are included:
$ python min_example.py > test.txt
$ vi test.txt
this is ^[[91mmatching^[[0m text
The real grep utility manages to output color to the terminal, yet its output can be piped to a text file without any funky escape sequence characters being included.
So my question: what is grep doing differently here, and how can I reproduce it so that I can output color yet still have "pipe-able" output?
Upvotes: 1
Views: 1110
Reputation: 5167
Turns out this is because grep isn't enabling color output when being piped. Its --color=auto
option only enables color output if stdout is connected to a terminal. Running the same test with grep --color=always ...
also results in ANSI escape characters being written to the text file.
I solved this problem by testing for sys.stdout.isatty()
before adding ANSI escape codes
Upvotes: 1