Skip to content
Advertisement

Strip positional information from subprocess std out

I am running a subprocess in python, capturing the std output:

results = subprocess.run(my_command, capture_output=True)

The command in question uses positional characters to update the number of packets sent, but in the resultant output, eg results.stdout, I see all of the updates.

Connecting (1 Packets Sent, 0 Packets Received, 0 Retries)x1b[2Kr[x1b[33m  0% x1b[0m] Connecting (1 Packets Sent, 0 Packets Received, 0 Retries)x1b[2Kr[x1b[33m  0% x1b[0m]

Ideally, I only want to save the final output, eg

[ERROR] Connecting (194 Packets Sent, 0 Packets Received, 193 Retries)

Not every one of the 194 interim lines. Is there a way do decode the stdout to only show the final string?

Advertisement

Answer

x1b[2K is the signal to erase the entire line. So this will get you the final thing printed:

lastline = output.rfind('x1b[2K')
output = output[lastline+4:]

That still leave the other ANSI codes, but since this uses a fixed set, those should be easy to remove.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement