[Tutor] console text positioning

Chris F.A. Johnson cfaj at freeshell.org
Sun Nov 13 01:57:47 CET 2005


On Sat, 12 Nov 2005, Bojan Raicevic wrote:

> I'm not sure how explain my problem, but I'll try.
>
> I want to make something that looks like console quiz.
> So it would look somehow like this:
>
> print "Question one (a,b,c,d): "
> #user should answer with a,b,c or d - anything else
> inputed should result without reaction - **my
> problem** I DON'T want to see in console output
> repeated questions like:
>
> Question one (a,b,c,d): ftbryj
> Question one (a,b,c,d): asdf
> Question one (a,b,c,d): a
> Question two (1,2,3,4): b
> Question two (1,2,3,4): 5
> Question two (1,2,3,4): 2
> Question three (a,b,c):
> ...
>
> I want to see only:
>
> Question one (a,b,c,d): a
> Question two (1,2,3,4): 3
> Question three (a,b,c): c
> Question four (1-10): 9
> ...
>
> So basicly, I want to see in console output only
> correct answers.
> Any idea how to do this ??


      ANSI is the standard for terminal control, so I usually code for
      that, but put it in a separate module so that other terminals can
      easily be accommodated.

      Here is a short example:

import sys
import os

COLUMNS = int(os.environ.get('COLUMNS'))
LINES = int(os.environ.get('LINES'))

ESC = '\033'
CSI = ESC + "["              ## Command Sequence Introducer
CLS = CSI + "H" + CSI + "2J" ## Clear screen
NA = CSI + "0m"              ## Clear text attributes

## set attributes
set_attr = CSI + "%sm"
set_bold = CSI + "1m"
set_ul   = CSI + "4m"
set_rev  = CSI + "7m"

def printat(row,col,arg=""):
     sys.stdout.write( CSI + str(row) + ";" + str(col) + 'H' + str(arg))

### Demo:
row = 10
col = 30
print CLS
printat( row, col, set_bold + "Hello, world" )
printat( LINES, COLUMNS - 6, NA + "Goodbye" )
printat( 1, 1)

-- 
    Chris F.A. Johnson                      <http://cfaj.freeshell.org>
    ===================================================================
    Author:
    Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)


More information about the Tutor mailing list