简体   繁体   中英

python: print using carriage return and comma not working

I need to print over one line in a loop (Python 3.x). Looking around on SO already, I put this line in my code:

print('{0} imported\r'.format(tot),)

However, it still prints multiple lines when looped through. I have also tried

sys.stdout.write('{0} imported\r'.format(tot))

but this doesn't print anything to the console...

Anyone know what's going on with this?

In the first case, some systems will treat \\r as a newline. In the second case, you didn't flush the line. Try this:

sys.stdout.write('{0} imported\r'.format(tot))
sys.stdout.flush()

Flushing the line isn't necessary on all systems either, as Levon reminds me -- but it's generally a good idea when using \\r this way.

If you want to overwrite your last line you need to add \\r (character return) and end="" so that you do not go to the next line.

values = range(0, 100)
for i in values:
    print ("\rComplete: ", i, "%", end="")
print ("\rComplete: 100%")

I prefer to use the solution of Jan but in this way:

values = range(0, 101)
for i in values:
  print ("Complete: ", i, "%", end="\r")
print ()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM