3

Possible Duplicate:
Piping data to Linux program which expects a TTY (terminal)

I want to display colors from script that is non interactive and I need to tell the shell that in fact my script is a terminal that support colors so command like ls --color=auto will display colors (ls have option --color=always but I would like to support for all posible commands that support colors as well).

I call my shell via python Popen. I've try to set TERM environment variable but It don't work.

subprocess.Popen(['/bin/bash', '-c', command],
                  env={'TERM':'xterm-color'},
                  stdout=subprocess.PIPE, stderr=subprocess.PIPE)

Is there a way to tell bash that I'm a terminal?

Community
  • 1
  • 1
jcubic
  • 61,973
  • 54
  • 229
  • 402

1 Answers1

1

Programs normally determine automatically (ls --color=auto) if there's a terminal connected. That goes by checking stdout/err file descriptors.

In case of you piping to and from python (as you are doing in your above example), programs will have their stdout/err connected to a pipe, not a terminal, and thus will normally not output color codes.

Try to redirect the process' stdout/err directly to the attached terminal, not back to your python app. If that's not feasible (because you need the output in python--but in this case you normally don't want color codes anyway), you'll have to fiddle around setting up a pseudo terminal in python somehow.

Jo So
  • 25,005
  • 6
  • 42
  • 59
  • It would be great if you could elaborate on "That goes by checking stdout/err file descriptors." as it seems exactly what the question is. How is this `--color=auto` implemented? – The Godfather Jul 26 '21 at 09:16
  • @TheGodfather POSIX has a library call `isatty(int fd)`. E.g. call `isatty(STDOUT_FILENO)` and/or `isatty(STDERR_FILENO)`. That should do the job and is probably what most programs do. There might be other mechanisms, though. – Jo So Jul 27 '21 at 09:06
  • When python script is executed inside a PyCharm terminal, `isatty` would be False, however the terminal supports colors. – The Godfather Jul 28 '21 at 06:38
  • @TheGodfather How do you know that isatty would be False in PyCharm terminal? I don't know PyCharm and I don't know a different way of detecting a terminal. – Jo So Jul 29 '21 at 09:28
  • If you want to find out how it works, you could start here: https://github.com/c9/node-gnu-tools/blob/master/grep-src/src/main.c . Just look for "--color", "auto", "isatty", etc – Jo So Jul 29 '21 at 09:31
  • I run Python script which prints return value of `isatty`, obviously.... – The Godfather Jul 29 '21 at 16:08