Print in Python to stay in line

import os
import time

h = 0
s = 0
m = 0

while s <= 60:
    os.system('clear')
    print h, "hours", m, 'minutes', s, 'seconds'
    time.sleep(1)
    s += 1
    if s == 60:
        m += 1
        s = 0
    elif m == 60:
        h += 1
        m = 0
        s = 0

I have this code above. Everything works fine and does what it should do, but I want to make it print all the statements on one line. For example, it should print 0 hours 0 minutes 0 seconds, and then on the same line you should print 0 hours 0 minutes 1 second, and the second variable is the only thing that changes. How should I do it? I already tried using the os.system ('clear') command, but it does not work. Im working on mac osx 10.7.

+3
source share
3 answers

, . '\r' ( , ); , . , , OSX .

print . , ( , ). sys.stdout.write() , , sys.stdout.flush().

, . , , . , , ( '\x1b[K' , , , , ).

EL = '\x1b[K'  # clear to end of line
CR = '\r'  # carriage return
sys.stdout.write(("%d hours %d minutes %s seconds" + EL + CR) % (h, m, s))
sys.stdout.flush()

( ) curses.

import curses
curses.setupterm()
EL = curses.tigetstr('el')
CR = curses.tigetstr('cr')

CR OSX, , (, ), save_cursor (SC) restore_cursor (RC) :

sys.stdout.write(SC + "%d hours %d minutes %s seconds" + EL + RC % (h, m, s))
+3

:

print h, "hours", m, 'minutes', s, 'seconds', '\r'

Alfe : -)

+2

In Python 3, you can use code like this:

print("{} hours, {} minutes, {} seconds".format(h, m, s), end = "\r")
0
source

All Articles