tartley / colorama

Simple cross-platform colored terminal text in Python
BSD 3-Clause "New" or "Revised" License
3.52k stars 250 forks source link

Tools with colorama cannot be automated within Pycharm #307

Open phi1010 opened 3 years ago

phi1010 commented 3 years ago

Hello,

the detection of Pycharm introduced in #107 / #108 / #163 has some false-positives -- it actually should only determine whether the current script's output is redirected to a Pycharm Console Windows. However, the environment variable used is inherited for any subprocess, causing output redirected to other tools (xxd here) to be skewed:

$PYCHARM_HOSTED=1 python -c 'from colorama import init, Fore, Style ; init() ; print("foo")'  | xxd
00000000: 666f 6f0a 1b5b 306d                      foo..[0m

$ python -c 'from colorama import init, Fore, Style ; init() ; print("foo")'  | xxd
00000000: 666f 6f0a                                foo.

Given the following scenario:

1) Pycharm is used to debug mytestsuite.py 2) mytestsuite.py launches somewebserver.py 3) somewebserver.py parses output from coloredtool.py 4) coloredtool.py uses colorama.

In this scenario, I'd like to debug mytestsuite.py -- however, since it is running in Pycharm, coloredtool.py suddenly starts to output ANSI escapes in its stdout, and causes somewebserver.py to fail, which makes debugging any software like mytestsuite.py with any indirect dependencies to colorama rather hard. Even identifying the issue of this sudden and unexpected malfunction of the webserver can be quite time-consuming.

I'd suggest removing the detection of the PYCHARM_HOSTED variable -- I'm not sure if the Pycharm option is new; but PyCharm can optionally emulate a TTY if required, which causes os.isatty (on Ubuntu) to return true for stdin/stdout/stderr on the single TTY actually connected to Pycharm. This way, all other tools not connected directly to the Pycharm window can output unformatted text as expected; and users of colorama still can use formatting within Pycharm, if they change their run/debug configuration accordingly.

image

3tilley commented 2 years ago

This is the fix you probably need - https://github.com/tartley/colorama/pull/230

I'm kind of with you on detecting that env var for Pycharm, but it probably is the easiest solution as emulating ttys can be a bit flakey