mkorpela
mkorpela

Reputation: 4395

How to print terminal formatted output to a variable

Is there a method to print terminal formatted output to a variable?

print 'a\bb'
--> 'b'

I want that string 'b' to a variable - so how to do it?

I am working with a text string from telnet. Thus I want to work with the string that would be printed to screen.

So what I am looking for is something like this:

simplify_string('a\bb') ==> 'b'

Another example with a carriage return:

simplify_string('aaaaaaa\rbb') ==> 'bbaaaaa'

Upvotes: 5

Views: 756

Answers (1)

nneonneo
nneonneo

Reputation: 179422

This turns out to be quite tricky because there are a lot of terminal formatting commands (including e.g. cursor up/down/left/right commands, terminal colour codes, vertical and horizontal tabs, etc.).

So, if you want to emulate a terminal properly, get a terminal emulator! pyte (pip install pyte) implements a VT102-compatible in-memory virtual terminal. So, you can feed it some text, and then get the formatted text from it:

import pyte

screen = pyte.Screen(80, 24)
stream = pyte.ByteStream(screen)
stream.feed(b'xyzzz\by\rfoo')
# print the first line of text ('foozy')
print(screen.display[0].rstrip())

To handle multiple lines, just join all of the lines in the text (e.g. '\n'.join(row.rstrip() for row in screen.display).rstrip()).

Note that this doesn't handle trailing spaces, but those would be indistinguishable on a real terminal anyway.

Upvotes: 8

Related Questions