golang如何覆盖输出console,实现进度条

栏目: Go · 发布时间: 7年前

内容简介:golang如何覆盖输出console,实现进度条

在研究K6源代码的时候,发现有一个进度条,觉得不错,就研究了一下怎么实现的,很简单,不说话,直接上代码

package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	for i := 0; i != 10; i = i + 1 {
		fmt.Fprintf(os.Stdout, "result is %d\r", i)
		time.Sleep(time.Second * 1)
	}
	fmt.Println("over")
}

最后输出的时候,添加\r,原理可以查看 https://stackoverflow.com/questions/15442292/golang-how-to-have-an-inplace-string-that-updates-at-stdout

stdout is a stream (io.Writer). You cannot modify what was already written to it. What can be changed is how is that stream represented in case it is printed to a terminal. Note that there’s no good reason to assume this scenario. An user can e.g. redirect stdout to a pipe or to a file at will. So the proper approach is to first check

if the stdout is going to a terminal

what is that terminal procedure to overwrite a line/a screen

Both of the above is out of this question scope, but let’s assume a terminal realy is our device. Then usually printing

fmt.Printf(“\rOn %d/10″, i)

will overwrite the previous line in the terminal. \r stands for a carriage return, implemented by many terminals as moving the cursor to the beginning of the current line, hence providing the “overwrite line” facility.

As an example of an “other” terminal with a differently supported ‘overwriting’, here is an example at the playground.


以上所述就是小编给大家介绍的《golang如何覆盖输出console,实现进度条》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

企业应用架构模式

企业应用架构模式

Martin Fowler / 王怀民、周斌 / 机械工业出版社 / 2010-4 / 59.00元

《企业应用架构模式》作者是当今面向对象软件开发的权威,他在一组专家级合作者的帮助下,将40多种经常出现的解决方案转化成模式,最终写成这本能够应用于任何一种企业应用平台的、关于解决方案的、不可或缺的手册。《企业应用架构模式》获得了2003年度美国软件开发杂志图书类的生产效率奖和读者选择奖。《企业应用架构模式》分为两大部分。第一部分是关于如何开发企业应用的简单介绍。第二部分是《企业应用架构模式》的主体......一起来看看 《企业应用架构模式》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具