Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python打印显示进度条_Python_Python 3.x - Fatal编程技术网

如何使用Python打印显示进度条

如何使用Python打印显示进度条,python,python-3.x,Python,Python 3.x,我想通过在同一行上打印来显示循环的进度。下面的代码段工作正常 for x in range(10): print("Step " + str(x), '\r', end='', flush=True) 但当我在主代码中使用它时,它似乎不起作用 epochs = 200 for epoch in range(epochs): # start of epoch start_time = time.time() print("Epoch:

我想通过在同一行上打印来显示循环的进度。下面的代码段工作正常

for x in range(10):
    print("Step " + str(x), '\r', end='', flush=True)
但当我在主代码中使用它时,它似乎不起作用

epochs = 200
for epoch in range(epochs):
    # start of epoch
    start_time = time.time()
    print("Epoch: {}/{}".format(epoch+1, epochs))
    for step, train_batch in enumerate(train_gen):
        curr_loss = train_step(train_batch)
        percent_completed = step // (len(train_gen)//20)
        time_elapsed = time.time() - start_time
        print(f"{step}/{len(train_gen)}: [{'=' * percent_completed + '>' + '.'*(20-percent_completed)}] - ETA: {time_elapsed}s - Loss: {curr_loss}", '\r', end='', flush=True)
       
上述代码的输出如下所示

为什么不在嵌套的for循环中显示print语句?

尝试以下操作:

for epoch in range(epochs):
    # start of epoch
    start_time = time.time()
    print("Epoch: {}/{}".format(epoch + 1, epochs))
    for step, train_batch in enumerate(train_gen, 1):
        curr_loss = train_step(train_batch)
        percent_completed = int(step / (len(train_gen) / 20))
        time_elapsed = time.time() - start_time
        print(
            f"{step}/{len(train_gen)}: [{'=' * percent_completed + '>' + '.' * (20 - percent_completed)}] - ETA: {time_elapsed}s - Loss: {curr_loss}",
            '\r', end='', flush=True)
你有错误:

ZeroDivisionError:整数除法或模零除法

在这一行

percent_completed = step // (len(train_gen)//20)

看起来,屏幕截图来自print(“Epoch:{}/{}.format(Epoch+1,epochs))语句,并且“end=''”不在那里。您是否检查了“train\u gen”是否为None?“train\u gen”是否为NoneBTW:而不是
'\r',end=''
您可以直接使用
end='\r'
首先检查
train\u get
是否为空。对于的空列表-将永远不会执行循环,也永远不会打印任何内容。