subprocess stdout without colors

Question:

I am running a command line tool that returns a coloured output (similar to ls --color). I run this tool via subprocess:

process = subprocess.run(['ls --color'], shell=True, stdout=subprocess.PIPE)
process.stdout.decode()

But the result is, of course, with the color instructions like x1b[mx1b[m which makes further processing of the output impossible.

How can I remove the colouring and use pure text?

Asked By: Michael Dorner

||

Answers:

You example worked for me. You can also open the file with just 'w' and specify the encoding:

import subprocess

with open('output.txt', mode='w', encoding='utf-8') as file:
    process = subprocess.run(['ls', '-l'], stdout=file)

Answered By: ukBaz

This works on my win10 and python 3.11 machine. Your command runs without any issue:
In my IDE I can’t see color, but this command works also subprocess.run(["ls", "--color=none"], shell=True, stdout=subprocess.PIPE).

Valid arguments are on my machine:

  • ‘never’, ‘no’, ‘none’
  • ‘auto’, ‘tty’, ‘if-tty’
  • ‘always’, ‘yes’, ‘force’

Code:

import subprocess

process = subprocess.run(["ls", "-la"], shell=True, stdout=subprocess.PIPE)

with open("dirList.txt", 'w') as f:
    f.write(process.stdout.decode())

Output:
total 14432

drwxr-xr-x 1 Hermann Hermann       0 Nov 19 08:00 .
drwxr-xr-x 1 Hermann Hermann       0 Aug 28  2021 ..
-rw-r--r-- 1 Hermann Hermann       0 Jan 28 09:25 .txt
-rw-r--r-- 1 Hermann Hermann    1225 Jan  6 00:51 00_Template_Program.py
-rw-r--r-- 1 Hermann Hermann     490 Jan 15 23:33 8859_1.py
-rw-r--r-- 1 Hermann Hermann     102 Jan 15 23:27 8859_1.xml
Answered By: Hermann12
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.