jowan sebastian
jowan sebastian

Reputation: 253

Print to a specific line on stdout using Python

I would like to print to a specific line on stdout using Python.

Say.. I have a loop within a loop. Currently it prints this :

a0,b0,c0,a1,b1,c1,a2,b2,c2,

But actually I want it to print this :

a0,a1,a2,
b0,b1,b2,
c0,c1,c2,

the code looks something like this

import sys

ar = ['a', 'b', 'c']
for i in ar:
    c = 1
    while c < 4:
        sys.stdout.write('%s%s,' % (i, c))
        c += 1

Is there a way of identify the line ? eg print to line X ?

Or - can I write 3 lines to stdout (using '\n'), then go back and overwrite line 1 ?

note: I don't just want to achieve the above ! I can do that by altering the loop - the question is about identifying different lines of stdout and writing to them, if possible

Thanks

Upvotes: 2

Views: 2529

Answers (1)

jowan sebastian
jowan sebastian

Reputation: 253

as @hop suggested, the blessings library looks great for this.

For example

from blessings import Terminal

term = Terminal()
with term.location(0, term.height - 1):
    print 'Here is the bottom.'

and in my example, something along the lines of the below works. It does give the output I was looking for.

from blessings import Terminal

term = Terminal()

print '.'
print '.'
print '.'


ar = ['a', 'b', 'c']
x = 1
for i in ar:
    c = 1
    while c < 4:
        with term.location(c*3-3, term.height - (5-x)):
            print str(i)+str(c-1)+','
        c += 1   
    x += 1

gives:

a0,a1,a2,
b0,b1,b2,
c0,c1,c2,

Upvotes: 1

Related Questions