2 Replies - 6323 Views - Last Post: 05 February 2012 - 11:17 AM Rate Topic: -----

#1 NotarySojac  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 53
  • View blog
  • Posts: 428
  • Joined: 30-September 10

How to spice up the user interface in command line programs

Posted 04 February 2012 - 01:56 PM

You know how when you run a command like `wget` you get a little progress bar, and the percentage completion updates with out creating new lines of output? How is that done? What is that even called? I'm thinking of making a basic little IRC client that can be run over an ssh connection for a project that I've been working on, and I have a feeling that's the concept I need in order to get a pleasant UI.
Is This A Good Question/Topic? 0
  • +

Replies To: How to spice up the user interface in command line programs

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2089
  • View blog
  • Posts: 3,181
  • Joined: 21-June 11

Re: How to spice up the user interface in command line programs

Posted 05 February 2012 - 02:40 AM

To create a wget-like progress bar, all you need to do is overwrite the same line again and again. You can do that by printing a carriage return to return to the beginning of the line and then just printing the new contents of the line (without a line break at the end, so you'll stay in the same line).

If the new contents of the line are shorter than the old contents, you'll need to pad it with spaces or else the rest of the old contents will still be visible (i.e. if you overwrite "bla" with "\rxy" it will read as "xya", so you need to use "\rxy " instead).

Keep in mind that terminal IO is line-buffered by default, so if you print a line without a line break, you'll need to flush $stdout or disable buffering. Here's an example:

puts "Progress:"
max = 50
0.upto(max) do |i|
  print "\r|", "="*i, ">", " "*(max-i), "|"
  $stdout.flush
  sleep 0.1
end

puts "Countdown:"
100.downto(0) do |i|
  printf("\r%3d", i)
  $stdout.flush
  sleep 0.1
end

puts "Boom!"



However while that little trick is perfectly sufficient to create progress bars or other updating status information, it's hardly enough to create a pleasant user interface for an IRC client. For that you should look into the ncurses library.
Was This Post Helpful? 3
  • +
  • -

#3 NotarySojac  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 53
  • View blog
  • Posts: 428
  • Joined: 30-September 10

Re: How to spice up the user interface in command line programs

Posted 05 February 2012 - 11:17 AM

Extremely helpful post, thank you =)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1