Author Topic: [Java snippet] CLI animated progress bar  (Read 4453 times)

0 Members and 1 Guest are viewing this topic.

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
[Java snippet] CLI animated progress bar
« on: April 27, 2013, 08:51:19 pm »
This little code snippet might come in handy for command line tools that need to show a progress.
It uses carriage return character (/r) to move the cursor back to the beginning of the current line thus overwriting the content afterwards.
This way it can show a progress animation. Just try it out.

Example how it looks like:

Code: [Select]
[===============>                                   ]30%
And after a few seconds:

Code: [Select]
[===================================>               ]70%
I tried to make the code flexible so you can customize it easily (like changing the characters for drawing the progress bar, changing the progress bar width).

Code and sample usage is shown below.

Code: [Select]
public class ProgressBar {

    private final int width;
    private String barStart = "[";
    private String barEnd = "]";
    private String arrowBody = "=";
    private String arrowEnd = ">";

    public ProgressBar(int width) {
        this.width = width;
    }

    public ProgressBar(int width, String barStart, String barEnd, String arrowBody,
            String arrowEnd) {
        this.barStart = barStart;
        this.barEnd = barEnd;
        this.arrowBody = arrowBody;
        this.arrowEnd = arrowEnd;
        this.width = width;
    }

    public void printProcessBar(int percent) {
        int processWidth = percent * width / 100;
        System.out.print("\r" + barStart);
        for (int i = 0; i < processWidth; i++) {
            System.out.print(arrowBody);
        }
        System.out.print(arrowEnd);
        for (int i = processWidth; i < width; i++) {
            System.out.print(" ");
        }
        System.out.print(barEnd + percent + "%");
    }

    public static void main(String[] args) throws InterruptedException {
        ProgressBar bar = new ProgressBar(50);
        for (int i = 0; i <= 10; i++) {
            Thread.sleep(600);
            bar.printProcessBar(i * 10);
        }
        System.out.println();
    }

}

Offline parad0x

  • VIP
  • Royal Highness
  • *
  • Posts: 638
  • Cookies: 118
    • View Profile
Re: [Java snippet] CLI animated progress bar
« Reply #1 on: May 17, 2013, 01:35:49 pm »
Thanks Deque,was searching for something like this.
It'll be useful in my project.
rep+
« Last Edit: May 17, 2013, 01:37:49 pm by parad0x »

Offline Kulverstukas

  • Administrator
  • Zeus
  • *
  • Posts: 6627
  • Cookies: 542
  • Fascist dictator
    • View Profile
    • My blog
Re: [Java snippet] CLI animated progress bar
« Reply #2 on: May 17, 2013, 05:48:22 pm »
You never stop to amaze me. Great work, I'll for sure be using this. +1

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
Re: [Java snippet] CLI animated progress bar
« Reply #3 on: May 17, 2013, 09:43:19 pm »
Thank you and you are welcome.
One thing I have to add if you use Eclipse: It doesn't work in the Eclipse console, because it isn't capable of processing the carriage return correctly.
For testing the code you should use the terminal of your OS.

Offline 3vilp4wn

  • Serf
  • *
  • Posts: 46
  • Cookies: 11
  • :D
    • View Profile
    • Evil Ninja Hackers
Re: [Java snippet] CLI animated progress bar
« Reply #4 on: May 17, 2013, 10:44:22 pm »
Huh, looks cool, I'm gonna try to port this to python.
Nice job, I was wanting to do something like this for a while.
+1

EDIT:
Here's what I've got [WIP]:

Code: [Select]
import sys
import time

def progbar(steps, timestep, beginbar, endbar, bartype, notbartype):
    sys.stdout.write('')
    for prog in range(1, steps):
        progtext = ''
        for i in range(1, prog):
            progtext = progtext + bartype[i % len(bartype)]
        progtext = progtext + notbartype * (steps - prog - 1)
        sys.stdout.write('\r' + beginbar + progtext + endbar)
        sys.stdout.flush()
        time.sleep(timestep)
    print '\n'


progbar(25, 0.1, '[', ']', '=--=', ' ')
progbar(25, 0.1, '[', ']', '_--_', ' ')
progbar(25, 0.1, '[', ']', '---^', ' ')
progbar(25, 0.1, '[', ']', ' -.- ', ' ')
progbar(25, 0.1, '[', ']', '    YOU ARE AN IDIOT!    ', ' ')
progbar(25, 0.1, '[', ']', '........ LOADING .........', ' ')
progbar(25, 0.1, '[', ']', '=', ' ')
progbar(25, 0.1, '{', '}', '*', ' ')
progbar(25, 0.1, '(', ')', '#', '-')
progbar(25, 0.1, '<', '>', '.', '_')
progbar(25, 0.1, '/', '/', '/', '\\')
progbar(25, 0.1, '[', ']', '~', '-')
progbar(25, 0.1, ' ', ' ', '-', ' ')
progbar(25, 0.1, '|', '|', '-=', ' ')

raw_input('')

I want to make multithreaded with a screenlock and cool shit like that, but like I said, WIP.
« Last Edit: May 17, 2013, 11:41:09 pm by 3vilp4wn »
Shooting is not  too good for my enemies.

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
Re: [Java snippet] CLI animated progress bar
« Reply #5 on: May 18, 2013, 08:52:40 am »
Huh, looks cool, I'm gonna try to port this to python.
Nice job, I was wanting to do something like this for a while.
+1

EDIT:
Here's what I've got [WIP]:

Code: [Select]
import sys
import time

def progbar(steps, timestep, beginbar, endbar, bartype, notbartype):
    sys.stdout.write('')
    for prog in range(1, steps):
        progtext = ''
        for i in range(1, prog):
            progtext = progtext + bartype[i % len(bartype)]
        progtext = progtext + notbartype * (steps - prog - 1)
        sys.stdout.write('\r' + beginbar + progtext + endbar)
        sys.stdout.flush()
        time.sleep(timestep)
    print '\n'


progbar(25, 0.1, '[', ']', '=--=', ' ')
progbar(25, 0.1, '[', ']', '_--_', ' ')
progbar(25, 0.1, '[', ']', '---^', ' ')
progbar(25, 0.1, '[', ']', ' -.- ', ' ')
progbar(25, 0.1, '[', ']', '    YOU ARE AN IDIOT!    ', ' ')
progbar(25, 0.1, '[', ']', '........ LOADING .........', ' ')
progbar(25, 0.1, '[', ']', '=', ' ')
progbar(25, 0.1, '{', '}', '*', ' ')
progbar(25, 0.1, '(', ')', '#', '-')
progbar(25, 0.1, '<', '>', '.', '_')
progbar(25, 0.1, '/', '/', '/', '\\')
progbar(25, 0.1, '[', ']', '~', '-')
progbar(25, 0.1, ' ', ' ', '-', ' ')
progbar(25, 0.1, '|', '|', '-=', ' ')

raw_input('')

I want to make multithreaded with a screenlock and cool shit like that, but like I said, WIP.

This isn't really reuseable because you have the sleep in there.
I imagine I have to do some work in the background and the progress bar shall show the progress of my work, so I use it and instead of working I sleep all the time and only change the progress value. :P

But good idea to port it.

Offline Kulverstukas

  • Administrator
  • Zeus
  • *
  • Posts: 6627
  • Cookies: 542
  • Fascist dictator
    • View Profile
    • My blog
Re: [Java snippet] CLI animated progress bar
« Reply #6 on: May 18, 2013, 04:49:16 pm »
Here's a nice snippet for python, made by 10n1z3d. I can't remember if he posted this on evilzone, but I can't find it. I have gotten it from intern0t I think.
This is a work indicator, for when you don't know the progress.

Code: (python) [Select]
#!/usr/bin/env python
#
# Simple circle work indicator (for CLI).
#
# Copyright (C) 2010 10n1z3d <10n1z3d[at]w[dot]cn>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import sys, time
from threading import Thread


class WorkIndicator(Thread):
    def __init__(self, text=None):
        self.chars = ['/', '-', '\\', '|']
        self.index = 0
        self.text = text if text else 'Working...'
        self.stopping = False
        Thread.__init__(self)
       
    def run(self):
        while not self.stopping:
            if self.index >= len(self.chars): self.index = 0
            sys.stdout.write('\r{0} {1}'.format(self.text, self.chars[self.index]))
            sys.stdout.flush()
            self.index += 1
            time.sleep(0.1)
           
    def stop(self):
        self.stopping = True

# example usage

indicator = WorkIndicator(text='Testing...')
indicator.start()
time.sleep(5)     # simulate some work
indicator.stop()

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
Re: [Java snippet] CLI animated progress bar
« Reply #7 on: May 18, 2013, 06:51:32 pm »
Here's a nice snippet for python, made by 10n1z3d. I can't remember if he posted this on evilzone, but I can't find it. I have gotten it from intern0t I think.
This is a work indicator, for when you don't know the progress.

Code: (python) [Select]
#!/usr/bin/env python
#
# Simple circle work indicator (for CLI).
#
# Copyright (C) 2010 10n1z3d <10n1z3d[at]w[dot]cn>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import sys, time
from threading import Thread


class WorkIndicator(Thread):
    def __init__(self, text=None):
        self.chars = ['/', '-', '\\', '|']
        self.index = 0
        self.text = text if text else 'Working...'
        self.stopping = False
        Thread.__init__(self)
       
    def run(self):
        while not self.stopping:
            if self.index >= len(self.chars): self.index = 0
            sys.stdout.write('\r{0} {1}'.format(self.text, self.chars[self.index]))
            sys.stdout.flush()
            self.index += 1
            time.sleep(0.1)
           
    def stop(self):
        self.stopping = True

# example usage

indicator = WorkIndicator(text='Testing...')
indicator.start()
time.sleep(5)     # simulate some work
indicator.stop()

Thanks for the snippet. Useful.

Offline 3vilp4wn

  • Serf
  • *
  • Posts: 46
  • Cookies: 11
  • :D
    • View Profile
    • Evil Ninja Hackers
Re: [Java snippet] CLI animated progress bar
« Reply #8 on: May 20, 2013, 01:44:03 am »
Alright, here's a non-crappy version  :) :


Code: [Select]
import sys
from threading import Thread
import time


class progressbar(Thread):
    def __init__(self, steps=50, beginbar='[', endbar=']', bartype='=', notbartype=' '):
        self.stopping = False
        self.prog = 1
        self.steps = steps
        self.beginbar = beginbar
        self.endbar = endbar
        self.bartype = bartype
        self.notbartype = notbartype
        Thread.__init__(self)
       
    def run(self):
        while not self.stopping:
            sys.stdout.write('')
            progtext = ''
            for i in range(1, self.prog):
                progtext = progtext + self.bartype[i % len(self.bartype)]
            for i in range(len(progtext)+1, self.steps-1):
                progtext = progtext + self.notbartype[i % len(self.notbartype)]
            sys.stdout.write('\r' + self.beginbar + progtext + self.endbar)
            sys.stdout.flush()
            time.sleep(0.5)
           
    def stop(self):
        self.stopping = True
        print ''

    def setprog(self, progto):
        self.prog = progto


pbar = progressbar(50)
pbar.start()
for progress in range(1, 50):
    time.sleep(1) #Working...
    pbar.setprog(pbar.prog+1) #Make the progress bar bigger.
pbar.stop()
Shooting is not  too good for my enemies.