How do command line tools change their output after outputting it?

后端 未结 4 972
北恋
北恋 2021-02-13 18:24

I\'ve noticed that a lot of command line tools, wget for example, will show progress as a number or progress bar that advances as a process is completed. While the question isn\

4条回答
  •  野的像风
    2021-02-13 18:34

    Just print a CR (without a newline) to overwrite a line. Here is an example program in perl:

    #!/usr/bin/env perl
    
    $| = 1;
    
    for (1..10) {
      print "the count is: $_\r";
      sleep(1)
    }
    

    I've also disabled output buffering ($| = 1) so that the print command sends its output to the console immediately instead of buffering it.

    Haskell example:

    import System.IO
    import Control.Monad
    import Control.Concurrent
    
    main = do
      hSetBuffering stdout NoBuffering
      forM_ [1..10] $ \i -> do
        putStr $ "the count is: " ++ show i ++ "\r"
        threadDelay 1000000
    

提交回复
热议问题