控制台简单进度指示

#0

The simplest way would be to do what wget and other programs do: printing out a carriage return and an ANSI erase-line code before the progress information, thus returning the cursor to the start of the line and replacing the existing text. For example:

import Control.Monad
import Control.Concurrent
import System.IO
import Text.Printf

putProgress :: String -> IO ()
putProgress s = hPutStr stderr $ "\r\ESC[K" ++ s

drawProgressBar :: Int -> Rational -> String
drawProgressBar width progress =
  "[" ++ replicate bars '=' ++ replicate spaces ' ' ++ "]"
  where bars = round (progress * fromIntegral width)
        spaces = width - bars

drawPercentage :: Rational -> String
drawPercentage progress = printf "%3d%%" (truncate (progress * 100) :: Int)

main :: IO ()
main = do
  forM_ [0..10] $ \i -> do
    let progress = fromIntegral i / 10
    putProgress $ drawProgressBar 40 progress ++ " " ++ drawPercentage progress
    threadDelay 250000
  putProgress "All done."
  hPutChar stderr '\n'

The key thing here is to not print a newline, so that you can return to the start of the line on the next progress update.

Of course, you could just print out the percentage here and drop the bar, but a bar is cooler :)

#1

If I want something really quick and dirty, what I tend to do is just print a sequence of dots. Every time there's been "a bit more" progress I just write another dot (with no newline). I tune the measure of "a bit of progress" so that the dots come on about the time scale of a dot per second. Not very sophisticated, but it shows the program is doing something.

If you actually have some sort of measure of how much total "progress" there will be (I often don't, but this is suggested by your mention of percentages), then you can just declare the whole program to be X dots, and print one every time you make 1/X progress.

推荐文章

【DevOps】在CentOS中安装Rancher2,并配置kubernetes集群

【DevOps】在CentOS中安装Rancher2,并配置kubernetes集群

推荐文章

kubernetes系列:(二)、kubernetes部署mysql(单节点)

kubernetes系列:(二)、kubernetes部署mysql(单节点)

推荐文章

如何设置jquery选项卡以形成100%的高度?

如何设置jquery选项卡以形成100%的高度?

推荐文章

Rails应用程序已经部署并运行,但是MySQL数据库看起来是空的

Rails应用程序已经部署并运行,但是MySQL数据库看起来是空的

推荐文章

Docker image 和 volume 的关系

Docker image 和 volume 的关系

推荐文章

如果条件允许,NANT构建脚本,

如果条件允许,NANT构建脚本,

推荐文章

Docker容器技术的核心原理

Docker容器技术的核心原理

推荐文章

actionscript httpservice身份验证弹出菜单

actionscript httpservice身份验证弹出菜单

推荐文章

如何在Prototype中将多个参数传递给onSuccess函数?

如何在Prototype中将多个参数传递给onSuccess函数?

推荐文章

Docker 开篇2 | 树莓派安装docker 续

Docker 开篇2 | 树莓派安装docker 续

推荐文章

更改PHP函数的默认字符集,如“htmlspecialchars”

更改PHP函数的默认字符集,如“htmlspecialchars”

推荐文章

如何在AIR应用程序中隐藏视图堆栈?

如何在AIR应用程序中隐藏视图堆栈?

推荐文章

docker 容器的使用

docker 容器的使用

推荐文章

开发iPhone游戏时有什么“问题”?

开发iPhone游戏时有什么“问题”?

推荐文章

docker 安装kafka(快速)

docker 安装kafka(快速)

推荐文章

甲骨文左外联接

甲骨文左外联接