I'm working on an interactive shell where the user is entering some text, and get t开发者_如何学Goext back in a way that looks like a conversation. On recent SMS UIs on androids and iphones, you can see text aligned to the left for the text you wrote, and text aligned to the right for the text you received.
This is the effect I want to achieve, but in a Linux shell (without fancy graphics, just the flow of inputs and outputs).
I'm well aware of the format()
and rjust()
methods but they require to know the number of characters your want to pad the value with, and I don't know the width of the current shell.
I'm not limited in the lib I can install or use and I'm mainly aiming the Linux platform, thought having something cross platform is always nice.
Use curses.
Use window.getmaxyx()
to get the terminal size.
Another alternative:
import os
rows, cols = os.popen('stty size', 'r').read().split()
As already noted, use curses. For simple cases, if you don't want to use curses, you may use COLUMNS
environment variable (more here).
If multiple lines of output need to be right justified, then a combination of:
- Getting the window width: How to get Linux console window width in Python
- textwrap.wrap
- Using rjust
Something like:
import textwrap
screen_width = <width of screen>
txt = <text to right justify>
# Right-justifies a single line
f = lambda x : x.rjust(screen_width)
# wrap returns a list of strings of max length 'screen_width'
# 'map' then applies 'f' to each to right-justify them.
# '\n'.join() then combines them into a single string with newlines.
print '\n'.join(map(f, textwrap.wrap(txt, screen_width)))
精彩评论