How can I print over the current line in a command

2019-01-06 14:26发布

On Unix, I can either use \r (carriage return) or \b (backspace) to print over text already visible in the shell (i.e. overwrite the current line again).

Can I achieve the same effect in a Windows command line from a Python script?

I tried the curses module but it doesn't seem to be available on Windows.

9条回答
太酷不给撩
2楼-- · 2019-01-06 14:48

Thanks for all the useful answers in here guys. I needed this :)

I found nosklo's answer particularly useful, but I wanted something fully contained within a function by passing the desired output as a parameter. Also, I didn't really need the timer, since I wanted the printing to take place after a specific event).

This is what did the trick for me, I hope someone else finds it useful:

import sys

def replace_cmd_line(output):
    """Replace the last command line output with the given output."""
    sys.stdout.write(output)
    sys.stdout.flush()
    sys.stdout.write('\r')
    sys.stdout.flush()
查看更多
唯我独甜
3楼-- · 2019-01-06 14:52

On Windows (python 3), it seems to work (not using stdout directly):

import sys

for i in reversed(range(0,20)):
  time.sleep(0.1)
  if(i == 19):
    print(str(i), end='', file=sys.stdout)
  else:
    print("\r{0:{width}".format(str(i), width = w, fill = ' ', align = 'right'), end='', file=sys.stdout)
  sys.stdout.flush()
  w = len(str(i))

The same line is updated everytime print function is called.

This algorithm can be improved, but it is posted to show what you can do. You can modify the method according to your needs.

查看更多
Explosion°爆炸
4楼-- · 2019-01-06 14:55

Easiest way is to use two \r - one at the beginning and one at the end

for i in range(10000):
    print('\r'+str(round(i*100/10000))+'%  Complete\r'),

It will go pretty quickly

查看更多
登录 后发表回答