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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With