ehi*_*ird 23
最简单的方法是执行wget和其他程序的操作:在进度信息之前打印回车符和ANSI擦除行代码,从而将光标返回到行的开头并替换现有文本.例如:
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'
Run Code Online (Sandbox Code Playgroud)
这里的关键是不打印换行符,以便您可以在下一个进度更新时返回到行的开头.
当然,你可以在这里打印出百分比然后放下吧,但是酒吧很酷:)
归档时间: |
|
查看次数: |
1361 次 |
最近记录: |