水平打印命令行进度条
Print command-line progress bar horizontally
#!/usr/bin/python
import time
count = 5
temp = True
while temp:
if count < 1:
print "done",
temp = False
else:
print "*"
time.sleep(2)
count -= 1
输出:
*
*
*
*
*
done
请注意,输出中的“*”在屏幕上以 2 秒的间隔一个接一个地打印出来(这正是我想要的),我需要将其用作其他一些进度条代码。
我用了print "*",
然而输出是水平的,但它在程序执行后立即打印。
>>>* * * * * done
使用 end
关键字给出此错误。
File "progress_1_.py", line 11
print ("*",end = '')
^
SyntaxError: invalid syntax
Python 版本是 Python 2.7.5 .
我无法在这台产品机器上升级 Python,需要处理现有版本以获得所需的输出。
那么,考虑到以上情况,不是换行打印,而是每隔2秒水平打印一个接一个吗?
Python 2 的 print
语句不如 Python 3 中的函数灵活。
如果你使用了Python 3,你可以简单地指定结束字符以及是否立即刷新缓冲区,如下所示:
print("*", end="", flush=True)
但是,当您使用 Python 2 时,您不能使用 print
语句,而必须直接访问输出流对象:
import sys
def progress_print(character="*"):
sys.stdout.write(character)
sys.stdout.flush()
这将强制Python在一行完成之前不缓存打印数据,而是通过刷新缓冲区立即显示它。
您可以使用 python -u
跳过整个 python 进程的缓冲
或者当您需要使用 python 2 时,您也可以将 sys.stdout
替换为其他一些流,例如 wrapper,它会在每次调用后进行刷新。
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
import time
import sys
sys.stdout = Unbuffered(sys.stdout)
print '*',
time.sleep(2)
print '*'
这是一个简单的答案:
#!/usr/bin/python
import sys
import time
def wait(n):
time_counter = 0
while True:
time_counter += 1
if time_counter <= n:
time.sleep(1)
sys.stdout.write("*")
sys.stdout.flush()
else:
break
sys.stdout.write("\n")
wait(10)
Output:
**********
你可以随意修改。
#!/usr/bin/python
import time
count = 5
temp = True
while temp:
if count < 1:
print "done",
temp = False
else:
print "*"
time.sleep(2)
count -= 1
输出:
*
*
*
*
*
done
请注意,输出中的“*”在屏幕上以 2 秒的间隔一个接一个地打印出来(这正是我想要的),我需要将其用作其他一些进度条代码。
我用了
print "*",
然而输出是水平的,但它在程序执行后立即打印。>>>* * * * * done
使用
end
关键字给出此错误。File "progress_1_.py", line 11 print ("*",end = '') ^ SyntaxError: invalid syntax
Python 版本是 Python 2.7.5 .
我无法在这台产品机器上升级 Python,需要处理现有版本以获得所需的输出。
那么,考虑到以上情况,不是换行打印,而是每隔2秒水平打印一个接一个吗?
Python 2 的 print
语句不如 Python 3 中的函数灵活。
如果你使用了Python 3,你可以简单地指定结束字符以及是否立即刷新缓冲区,如下所示:
print("*", end="", flush=True)
但是,当您使用 Python 2 时,您不能使用 print
语句,而必须直接访问输出流对象:
import sys
def progress_print(character="*"):
sys.stdout.write(character)
sys.stdout.flush()
这将强制Python在一行完成之前不缓存打印数据,而是通过刷新缓冲区立即显示它。
您可以使用 python -u
或者当您需要使用 python 2 时,您也可以将 sys.stdout
替换为其他一些流,例如 wrapper,它会在每次调用后进行刷新。
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
import time
import sys
sys.stdout = Unbuffered(sys.stdout)
print '*',
time.sleep(2)
print '*'
这是一个简单的答案:
#!/usr/bin/python
import sys
import time
def wait(n):
time_counter = 0
while True:
time_counter += 1
if time_counter <= n:
time.sleep(1)
sys.stdout.write("*")
sys.stdout.flush()
else:
break
sys.stdout.write("\n")
wait(10)
Output:
**********
你可以随意修改。