How to preserve original color coding of output on the shell while doing a subprocess.Popen?

Asked By: Anonymous

I have a simple Python script which live-prints the output of a command. Following is the script:

#!/usr/bin/env python3
import subprocess

def RunSubProcess(process, process_args):
    process = subprocess.Popen([process, process_args], 
    while process.stdout.readable():
        line = process.stdout.readline()
        if not line:

RunSubProcess('ls', '-la')

The script works well for what it should do but it loses color coding of the output on my shell. If I type ls -la, I get the output well-colored. But if I run the above Python script, it gives the output uncolored.

Is there an argument to subprocess.Popen that could preserve color coding of the shell it’s running on?

I am running this Python script on a bash shell on MacOS with Python 3.9.0 installed.


Answered By: Anonymous

Many programs detect whether they are connecterd to a terminal, and switch to different behaviors for interactive use.

Some provide options to force interactive features (try ls --color=always but what exactly works depends on your platform; this is not standardized behavior. The macOS ls man page says to set CLICOLOR=yes in the environment) and others can be fooled into believing they are running interactively by using the pty library, or pexpect which is a higher-level package and somewhat easier to work with.

techinplanet staff

techinplanet staff

Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno