终端或控制台中的就地进度输出

时间:2010-02-25 18:13:18

标签: ruby unix terminal ncurses

当您运行git clone时,它会更新进度。例如,收到的对象的百分比发生了变化。

user@athena:~/cloj/src$ git clone git://git.boinkor.net/slime.git
Initialized empty Git repository in /home/user/cloj/src/slime/.git/
remote: Counting objects: 15936, done.
remote: Compressing objects: 100% (5500/5500), done.
Receiving objects:  28% (4547/15936), 3.16 MiB | 165 KiB/s

这是如何完成的?它是否使用ncurses或更简单的东西,比如退格字符和常规字符输出的某种组合?

我对如何通过Ruby实现这种控制台输出特别感兴趣。

修改

我的原始问题已经回答了。但这是一个附录。例如,当您使用MPlayer时,它不仅会更新一行以显示当前进度,还会更新上一行行(例如,当您按下暂停时)。

 =====  PAUSE  =====
A:  79.9 (01:19.9) of 4718.0 ( 1:18:38.0)  0.3% 

如何在原地更新两行输出?

5 个答案:

答案 0 :(得分:38)

使用回车。 '\ r'通常应该有用。

答案 1 :(得分:7)

git/progress.c

...
        eol = done ? done : "   \r";
...
                fprintf(stderr, "...%s", ..., eol);
                fflush(stderr);

Git只是发出回车而没有换行,终端将其解释为“移至第一列”。

答案 2 :(得分:4)

您必须使用其他方法(如Curses)来就地更新两行。

ablogaboutcode.com | web.archive.org

...和...

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/curses/rdoc/Curses.html

答案 3 :(得分:2)

我为多行输出更新编写了一个小类:

class ConsoleReset
  # Unix
  # Contains a string to clear the line in the shell
  CLR = "\e[0K"
  # ANSI escape sequence for hiding terminal cursor
  ESC_CURS_INVIS = "\e[?25l"
  # ANSI escape sequence for showing terminal cursor
  ESC_CURS_VIS   = "\e[?25h"
  # ANSI escape sequence for clearing line in terminal
  ESC_R_AND_CLR  = "\r#{CLR}"
  # ANSI escape sequence for going up a line in terminal
  ESC_UP_A_LINE = "\e[1A"

  def initialize
    @first_call = true
  end

  def reset_line(text = '')
    # Initialise ANSI escape string
    escape = ""

    # The number of lines the previous message spanned
    lines = text.strip.lines.count - 1

    # Clear and go up a line
    lines.times { escape += "#{ESC_R_AND_CLR}#{ESC_UP_A_LINE}" }

    # Clear the line that is to be printed on
    # escape += "#{ESC_R_AND_CLR}"

    # Console is clear, we can print!
    STDOUT.print escape if !@first_call
    @first_call = false
    print text
  end

  def hide_cursor
    STDOUT.print(ESC_CURS_INVIS)
  end

  def show_cursor
    STDOUT.print(ESC_CURS_VIS)
  end

  def test
    hide_cursor

    5.times do |i|
      line = ['===========================================']
      (1..10).each do |num|
        line << ["#{num}:\t#{rand_num}"]
      end
      line << ['===========================================']
      line = line.join("\n")
      reset_line(line)
      sleep 1
    end

    show_cursor

    puts ''
  end

  private
    def rand_num
      rand(10 ** rand(10))
    end
end

prydonius/spinning_cursor的启发。有关示例用法,请参阅test方法。

答案 4 :(得分:0)

Ruby有许多curses librbaries。我相信rbbcurse是最维护的。

相关问题