Python教程

代码笔记16 python中用print函数实现输出进度

本文主要是介绍代码笔记16 python中用print函数实现输出进度,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

目标

  在训练网络的时候,往往需要实现一个实时输出epoch、batch_id、loss的方法。当然我们可以一个epoch输出一次,但为了更好的了解loss的变化,我们可以每次迭代都输出一次。但每次print都会重启一行,这样一个epoch下来会输出很多行,非常的不方便。我们可以巧用print函数来实现这个功能。

print函数解析

  详情可以观看博客[1],使用print函数中的end以及\r来实现。
  同时这种方法还需要使用format函数来达到只更新输出中一部分内容的目标,详情可见noob网站[2].

实现

  我也是简单的实现了一下,在每个i迭代一次中,输出一遍j的值

import time

if __name__ == "__main__":
    for i in range(100):
        for j in range(10):
            if j == 9:
                time.sleep(0.5)  # sleep() for better show the change
                print('\r', "j = {:0>2}, i = {:0>3}".format(j, i), end='\n') 
                # j == 9 is the last iteration in i epoch, use end='\n' start a new line
            else:
                time.sleep(0.5)
                print('\r', "j = {:0>2}, i = {:0>3}".format(j, i), end='')

输出结果

 j = 09, i = 000
 j = 09, i = 001
 j = 09, i = 002
 j = 09, i = 003
 j = 09, i = 004
 j = 09, i = 005
 j = 09, i = 006
 j = 09, i = 007
 j = 09, i = 008
 j = 09, i = 009
 j = 03, i = 010

Refrences

[1] https://www.cnblogs.com/zzliu/p/10156658.html
[2] https://www.runoob.com/python/att-string-format.html

这篇关于代码笔记16 python中用print函数实现输出进度的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!