bash python中的'echo -en ...'是否有等效的功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/13211614/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there equivalent functionality for 'echo -en ...' in python?
提问by jbranchaud
Possible Duplicate:
Replace console output in python
可能的重复:
替换 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 fileis replaced with 2 filesand then with 3 filesand so forth.
我正在尝试编写一个程序来输出信息,包括对命令行的更新。我所说的更新是指,例如,如果程序正在处理文件,它可能会保留到目前为止处理的文件的更新计数。So1 file被替换为2 files,然后替换为3 files等等。
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:
这里有两个问题:
- From what I know from doctors, the echocommand is not portable at all.
- I want to do this in a python program, not with a bash file.
- 据我从医生那里得知,该echo命令根本不可移植。
- 我想在 python 程序中执行此操作,而不是使用 bash 文件。
Is there a way to achieve functionality similar to this using python?
有没有办法使用python实现与此类似的功能?
回答by poke
An equivalent implementation in Python would be this:
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('')
You need to use sys.stdout.writeas printby default adds a new-line. If you are using the print-function (Python 3, or by explicitely importing it in Python 2), you can also use print('text', end=''). Alternatively in Python 2, you can use the print-statement's feature to suppress the line termination like this: print 'text',
您需要使用sys.stdout.writeasprint默认情况下添加一个换行符。如果您使用的是打印功能(Python 3,或通过在 Python 2 中明确导入),您还可以使用print('text', end=''). 或者,在 Python 2 中,您可以使用打印语句的功能来抑制行终止,如下所示:print 'text',

