Python - 如何在for循环中显示两个计数器
Python - How to display two counters in for loops
我正在尝试实现下一个效果:
我有两个计数器,一个应该是 "Current" 计数器,它应该从 1 计数到 123,而控制台底部也应该有一个名为 "Total" 的计数器,它应该显示总数,例如234.
这是我的代码:
import sys
import time
n = 0
for _ in range(0, 5):
i = 1
for _ in range(0, 123):
sys.stdout.write("\r " + "Current: %d" % i)
sys.stdout.flush()
i = i + 1
n = n + 1
time.sleep(0.01)
print('')
sys.stdout.write("\rTotal: %d" % n)
time.sleep(0.5)
这几乎是我想要的,只是每次执行内部 for 循环时 "Total" 行都会被覆盖。所以应该总是只显示一个 "Total" 行与循环总数。
这可以在 Python 中实现吗?如何实现?
如果你真的想要两行,你可以使用CPL
(光标上一行)ANSI escape code将光标移动到上一行的开头。
import sys
import time
import colorama
print('')
total = 0
for _ in range(0, 5):
current = 1
sys.stdout.write("3[F")
for _ in range(0, 123):
sys.stdout.write("\rCurrent: %03d" % current)
sys.stdout.flush()
current += 1
total += 1
time.sleep(0.01)
sys.stdout.write("\nTotal: %d" % total)
sys.stdout.flush()
time.sleep(0.5)
请注意,在 Windows 上,您必须先导入 colorama
module。
控制台写入仅发生在一行中,因此它将清除 'total'。
一种方法是始终在下一行打印 'Total' 和 'Current'。
for _ in range(0, 123):
i = i + 1
sys.stdout.write("\r " + "Current: %d" % i)
n = n + 1
sys.stdout.write("\rTotal: %d" % n)
sys.stdout.flush()
或者,有一个单独的渲染循环(在另一个线程上)连续打印这些全局变量(当前和总计)。它将有自己的刷新率。
按照@Joost
的建议玩完诅咒后解决了
最终代码:
import time
import curses
stdscr = curses.initscr()
n = 0
b = 0
for _ in range(0, 5):
i = 1
for _ in range(0, 123):
stdscr.addstr(b, 0, "Current: %d" % i)
i = i + 1
n = n + 1
time.sleep(0.01)
stdscr.addstr(b+1, 0, "Total: %d" % n)
stdscr.refresh()
b = b + 1
我正在尝试实现下一个效果:
我有两个计数器,一个应该是 "Current" 计数器,它应该从 1 计数到 123,而控制台底部也应该有一个名为 "Total" 的计数器,它应该显示总数,例如234.
这是我的代码:
import sys
import time
n = 0
for _ in range(0, 5):
i = 1
for _ in range(0, 123):
sys.stdout.write("\r " + "Current: %d" % i)
sys.stdout.flush()
i = i + 1
n = n + 1
time.sleep(0.01)
print('')
sys.stdout.write("\rTotal: %d" % n)
time.sleep(0.5)
这几乎是我想要的,只是每次执行内部 for 循环时 "Total" 行都会被覆盖。所以应该总是只显示一个 "Total" 行与循环总数。
这可以在 Python 中实现吗?如何实现?
如果你真的想要两行,你可以使用CPL
(光标上一行)ANSI escape code将光标移动到上一行的开头。
import sys
import time
import colorama
print('')
total = 0
for _ in range(0, 5):
current = 1
sys.stdout.write("3[F")
for _ in range(0, 123):
sys.stdout.write("\rCurrent: %03d" % current)
sys.stdout.flush()
current += 1
total += 1
time.sleep(0.01)
sys.stdout.write("\nTotal: %d" % total)
sys.stdout.flush()
time.sleep(0.5)
请注意,在 Windows 上,您必须先导入 colorama
module。
控制台写入仅发生在一行中,因此它将清除 'total'。
一种方法是始终在下一行打印 'Total' 和 'Current'。
for _ in range(0, 123):
i = i + 1
sys.stdout.write("\r " + "Current: %d" % i)
n = n + 1
sys.stdout.write("\rTotal: %d" % n)
sys.stdout.flush()
或者,有一个单独的渲染循环(在另一个线程上)连续打印这些全局变量(当前和总计)。它将有自己的刷新率。
按照@Joost
的建议玩完诅咒后解决了最终代码:
import time
import curses
stdscr = curses.initscr()
n = 0
b = 0
for _ in range(0, 5):
i = 1
for _ in range(0, 123):
stdscr.addstr(b, 0, "Current: %d" % i)
i = i + 1
n = n + 1
time.sleep(0.01)
stdscr.addstr(b+1, 0, "Total: %d" % n)
stdscr.refresh()
b = b + 1