简体   繁体   中英

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'

This turns out to be quite tricky because there are a lot of terminal formatting commands (including eg 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 (eg '\\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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM