命令行工具在输出后如何更改输出? [英] How do command line tools change their output after outputting it?

查看:168
本文介绍了命令行工具在输出后如何更改输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,许多命令行工具,例如,wget将显示进度作为一个数字或进度条,随着进程完成进度。虽然问题不是真正的语言特定的,我使用最常用的命令行工具(C ++,Node.js,Haskell)我没有看到一种方法这样做。

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't really language-specific, out of the languages I use most often for command line tools (C++, Node.js, Haskell) I haven't seen a way to do this.

下面是一个例子,一个单行终端的三个快照wget下载一个文件:

Here's an example, three snapshots of a single line of Terminal as wget downloads a file:

除了其他信息,wget会显示进度条(< =>)下载文件。到目前为止所下载的数据量(6363,179561,316053)和当前的下载速度(10.7KB / s,65.8KB / s,63.0KB / s)也被更新。

Along with other information, wget shows a progress bar (<=>) that advances as it downloads a file. The amount of data downloaded so far (6363, 179561, 316053) and the current download speed (10.7KB/s, 65.8KB/s, 63.0KB/s) update as well. How is this done?

理想情况下,请包含一种或多种上述三种语言的代码示例。

Ideally, please include a code sample from one or more of the three languages mentioned above.

推荐答案

只需打印一个CR(不带换行符)即可覆盖一行。下面是perl中的示例程序:

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)
}

$ | = 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示例:

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

这篇关于命令行工具在输出后如何更改输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆