1

I'm working on an interactive shell where the user is entering some text, and get text 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.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Bite code
  • 578,959
  • 113
  • 301
  • 329
  • You can try using curses, or you can just assume that the terminal is 80 characters wide. – Rafe Kettler Apr 17 '11 at 16:12
  • "or you can just assume that the terminal is 80 characters wide" - no? We don't have 1990 anymore. – ThiefMaster Apr 17 '11 at 16:14
  • Not quite an exact duplicate, but have a look at this SO question (and the `stty size` command on *nix systems): http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python – Joe Kington Apr 17 '11 at 16:32

3 Answers3

2

Use curses.

Use window.getmaxyx() to get the terminal size.

Another alternative:

import os
rows, cols = os.popen('stty size', 'r').read().split()
the wolf
  • 34,510
  • 13
  • 53
  • 71
  • 1
    Just be aware that this will break if you decrease the size of the terminal window while running your program... http://bugs.python.org/issue984870 – Joe Kington Apr 17 '11 at 16:24
2

As already noted, use curses. For simple cases, if you don't want to use curses, you may use COLUMNS environment variable (more here).

abbot
  • 27,408
  • 6
  • 54
  • 57
0

If multiple lines of output need to be right justified, then a combination of:

  1. Getting the window width: How to get Linux console window width in Python
  2. textwrap.wrap
  3. 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)))
Community
  • 1
  • 1
mxsscott
  • 403
  • 3
  • 8