import sys
to = 20
digits = len(str(to - 1))
delete = "\b" * (digits)
for i in range(to):
print("{0}{1:{2}}".format(delete, i, digits), end="")
sys.stdout.flush()
In [9]: print?
Type: builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form: <built-in function print>
Namespace: Python builtin
Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
from sys import stdout
from time import sleep
for i in range(1,20):
stdout.write("\r%d" % i)
stdout.flush()
sleep(1)
stdout.write("\n") # move the cursor to the next line
import win32console, time
output_handle = win32console.GetStdHandle( win32console.STD_OUTPUT_HANDLE )
info = output_handle.GetConsoleScreenBufferInfo()
pos = info["CursorPosition"]
for i in "\\|/-\\|/-":
output_handle.WriteConsoleOutputCharacter( i, pos )
time.sleep( 1 )
或者,如果你想使用print(语句或函数,没有区别):
import win32console, time
output_handle = win32console.GetStdHandle( win32console.STD_OUTPUT_HANDLE )
info = output_handle.GetConsoleScreenBufferInfo()
pos = info["CursorPosition"]
for i in "\\|/-\\|/-":
print i
output_handle.SetConsoleCursorPosition( pos )
time.sleep( 1 )
import sys
class Printer():
"""Print things to stdout on one line dynamically"""
def __init__(self,data):
sys.stdout.write("\r\x1b[K"+data.__str__())
sys.stdout.flush()
为了在你的迭代循环中使用,你只需要调用如下代码:
x = 1
for f in fileList:
ProcessFile(f)
output = "File number %d completed." % x
Printer(output)
x += 1
tup = (1,2,3,4,5)
for n in tup:
print(n, end = " - ")
输出:
1 - 2 - 3 - 4 - 5 -
另一个例子:
list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for item in list_of_tuples:
print(item)
产出:
(1, 2)
('A', 'B')
(3, 4)
('Cat', 'Dog')
你甚至可以像这样解压元组:
list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
# Tuple unpacking so that you can deal with elements inside of the tuple individually
for (item1, item2) in list_of_tuples:
print(item1, item2)
产出:
1 2
A B
3 4
Cat Dog
另一种变化是:
list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for (item1, item2) in list_of_tuples:
print(item1)
print(item2)
print('\n')
_last_print_len = 0
def reprint(msg, finish=False):
global _last_print_len
# Ovewrites line with spaces.
print(' '*_last_print_len, end='\r')
if finish:
end = '\n'
# If we're finishing the line, we won't need to overwrite it in the next print.
_last_print_len = 0
else:
end = '\r'
# Store len for the next print.
_last_print_len = len(msg)
# Printing message.
print(msg, end=end)
例子:
for i in range(10):
reprint('Loading.')
time.sleep(1)
reprint('Loading..')
time.sleep(1)
reprint('Loading...')
time.sleep(1)
for i in range(10):
reprint('Loading.')
time.sleep(1)
reprint('Loading..')
time.sleep(1)
reprint('Loading...', finish=True)
time.sleep(1)