【问题标题】:python 3.x overwrite previous terminal linepython 3.x覆盖以前的终端行
【发布时间】:2015-01-22 17:08:47
【问题描述】:

我写了一个简单的程序来计算掷骰子的平均结果(毫无意义,但你必须从某个地方开始;P):

import random, time
from random import randrange

count = 0
total = 0
one_count = 0 

for x in range(10000000):
    random = randrange(1,7)
    count = count + 1
    total = total + random
    average = total / count
    percentage = one_count / count * 100
    if random == 1:
        one_count = one_count + 1
    print("the percentage of ones occurring is", percentage, "and the average outcome is", average)
#   time.sleep(1)

为了清理它,我希望输出覆盖上一行。我尝试了所有我能找到的东西,但我唯一能做到的就是打印到同一行而不删除以前的内容,方法是将最后一行更改为:

print("the percentage of ones occuring is", percentage, "and the average outcome is", average, "/// ", end="")

哪个输出:

the percentage of ones occuring is 0.0 and the average outcome is 4.0 /// the percentage of ones occuring is 0.0 and the average outcome is 4.5 /// the percentage of ones occuring is 0.0 and the average outcome is 3.6666666666666665 /// 

有什么想法吗?

【问题讨论】:

    标签: python python-3.x command-prompt overwrite


    【解决方案1】:

    在末尾添加\r。这样,您编写的下一行将从上一行的开头开始。然后刷新输出,使其立即显示。

    注意:如果下一行较短,剩余的字符仍会存在。

    【讨论】:

    • 在这种情况下,它可能与您的终端有关。你应该会看到curses
    • 我无法导入 curses:Traceback (most recent call last): File "/home/jakob/workspace/test/test.py", line 2, in <module> import curses File "/usr/local/lib/python3.4/curses/__init__.py", line 13, in <module> from _curses import * ImportError: No module named '_curses'
    • 您在开头添加了一个随机的_。只使用from curses import *
    • 不,“_curses”被“curses”导入:"""curses The main package for curses support for Python. Normally used by importing the package, and perhaps a particular module inside it. import curses from curses import textpad curses.initscr() ... """ from _curses import * import os as _os import sys as _sys ...抱歉没有格式化:)
    【解决方案2】:

    使用end='\r:

    for x in range(100000):
        rnd = randrange(1,7) # don't use random
        count += 1
        total = total + rnd
        average = total / count
        percentage = one_count / count * 100
        if rnd == 1:
            one_count += 1
        print("the percentage of ones occurring is {} and the average outcome is {}".format(percentage,average),end='\r')
        time.sleep(.1)
    

    另一方面,使用total = total + random 不是一个好主意,您正在导入随机模块并使用随机作为变量名。

    【讨论】:

    • 您忘记将第 7 行中的“random”更改为“rnd”,所以我只花了 10 分钟排除它为什么不能正常工作 :P 无论如何,我尝试添加 end="/ r" 之前,它仍然不起作用,没有任何变化......:/
    • 好吧,你得到了很好的教训,为什么不使用模块名称作为变量名称;),它为我将所有输出打印在一行上。你也在使用 time.sleep 吗?
    • 我想说谢谢,但评论框告诉我不要这样做:)
    • 我刚开始使用 PyDev,我的操作系统是 Linux Mint。
    • 终端必须像空闲一样被限制。你可以在其他任何地方运行它吗?
    猜你喜欢
    • 2015-10-16
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 2012-07-02
    • 2022-07-07
    • 2019-09-03
    • 2017-05-22
    相关资源
    最近更新 更多