为什么我的进度条要打印、完成,然后再打印、完成?

2024-10-01 13:32:47 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:好的,我把它放在另一个文件中,然后再次测试,结果很好。谢谢你们,还要特别感谢你们对重构代码的彻底破坏!你知道吗

我有一个完成的(工作)进度百分比,然后打印自己和任何周围的打印语句两次。你知道吗

我需要两份打印报表。注释掉printProgress(0, 100, suffix = 'complete')只会使它从1开始而不是0,并且仍然打印两次。你知道吗

注释掉printProgress(x + 1, 100, suffix = 'complete')会导致 testprintmpletetestprintmplete,这显然是不理想的。你知道吗

注释掉print('\r%s%% %s' % (percent, suffix), end = '\r')会导致 test\nprinttest\nprint,我认为这意味着问题在for循环的某个地方。但是在哪里?

这是我剩下的代码。你知道吗

def printProgress(iteration, total, suffix):

    # call in a loop to create terminal progress percentage
    # iteration - Required : current iteration (Int)
    # total     - Required : total iterations (Int)
    # suffix    - Optional : suffix string (Str)
    # decimals  - Optional : positive number of decimals in percent complete (Int)

    percent = ("{0:." + str(0) + "f}").format(100 * (iteration / float(total)))
    print('\r%s%% %s' % (percent, suffix), end = '\r')
    # print new line on completion
    if iteration == total:
        print()

print('test')
y = list(range(0, 100))
# start progress at 0
printProgress(0, 100, suffix = 'complete')

for x in y:
    time.sleep(.01)
    # update progress bar
    printProgress(x + 1, 100, suffix = 'complete')
print('print')```

# Here's my expected output:
test
100% complete
print

# Here's my actual output:
test
100% complete
print
test
100% complete
print

Tags: 代码intestforsuffixintendtotal