0

Possible Duplicate:
Replace console output in python

I am trying to write a program that outputs information including updates to the command line. What I mean by updates is, for example, if files are being processed by the program, perhaps it will keep an updated count of the files processed so far. So 1 file is replaced with 2 files and then with 3 files and so forth.

The following is a sample piece of code that counts out some files and then displays a loading bar:

#!/bin/bash

for a in {1..10}
do
    echo -ne " $a files processed.\r"
    sleep 1
done
echo ""
echo -ne '#####                     (33%)\r'
sleep 1
echo -ne '#############             (66%)\r'
sleep 1
echo -ne '#######################   (100%)\r'
echo -ne '\n'

Basically, the command line output gets periodically overwritten giving the effect of a primitive text-based animation in the terminal.

There are two problems here:

  1. From what I know from doctors, the echo command is not portable at all.
  2. I want to do this in a python program, not with a bash file.

Is there a way to achieve functionality similar to this using python?

4

1 回答 1

2

Python 中的等效实现是这样的:

import sys, time

for a in range(1,11):
    sys.stdout.write('\r {0} files processed.'.format(a))
    time.sleep(1)

print('')
sys.stdout.write('\r#####                     (33%)')
time.sleep(1)
sys.stdout.write('\r#############             (66%)')
time.sleep(1)
sys.stdout.write('\r#######################   (100%)')
print('')

您需要使用sys.stdout.writeasprint默认添加一个换行符。如果您正在使用打印功能(Python 3,或通过在 Python 2 中显式导入它),您也可以使用print('text', end=''). 或者,在 Python 2 中,您可以使用 print-statement 的功能来抑制行终止,如下所示:print 'text',

于 2012-11-03T17:35:35.140 回答