views:

65

answers:

1

I"m trying to make a simple text progress bar in windows console and also display utf8 characters.

The problem isn't that the unicode characters won't display, they will. It's that in order to make the unicode characters display I used a class to tell sys.stdout what to do. This has interfered with the normal flush() function.

How can I get this flush() funcionality back in the console and still use this unicode class?

#coding=<utf8>
import sys, os

#make windows console unicode friendly
if sys.platform == "win32":
    os.popen('chcp 65001')
    class UniStream(object):
        __slots__= "fileno", "softspace",
        def __init__(self, fileobject):
            self.fileno= fileobject.fileno()
            self.softspace= False

        def write(self, text):
            if isinstance(text, unicode):
                os.write(self.fileno, text.encode("utf_8"))
            else:
                os.write(self.fileno, text)
        def flush(self):
            self.flush()

    sys.stdout = UniStream(sys.stdout)
    sys.stderr = UniStream(sys.stderr)

def progress(num):
    sys.stdout.write("\r"+str(num)+"%    τοις εκατό...")
    sys.stdout.flush()


for i in xrange(2000):
    progress(i)


x = raw_input('done')
A: 

Maybe you should use the more primitive method of using backspace to remove previous number? Or do something like:

def progress(num): 
    sys.stdout.write("\r"+20*" "+"\r"+str(num)+"%    τοις εκατό...") 

to overwrite with spaces after return and do second return.

I do not see any flashing when I do this, it only works for me when running the code from command window, not double clicking.

#<coding=<utf8>
import sys, os, time
clear, percent ='', -1
def progress(num, maxvalue):
    global clear, percent
    p = 100 * num / maxvalue +1
    if p != percent:
        percent = p            
        for c in clear: sys.stdout.write(chr(8))
        clear = str(p)+"%    τοις εκατό..."
        sys.stdout.write(clear)

#make windows console unicode friendly
if sys.platform == "win32":
    os.popen('chcp 65001')
    class UniStream(object):
        __slots__= "fileno", "softspace",
        def __init__(self, fileobject):
            self.fileno= fileobject.fileno()
            self.softspace= False

        def write(self, text):
            if isinstance(text, unicode):
                os.write(self.fileno, text.encode("utf_8"))
            else:
                os.write(self.fileno, text)       

    sys.stdout = UniStream(sys.stdout)
    sys.stderr = UniStream(sys.stderr)

maxval=2000
for i in xrange(maxval):
    progress(i,maxval)
    time.sleep(0.02)

raw_input('done')
Tony Veijalainen
You're awesome! Thanks. Work, wonderfully.From your code, it looks like the important part is where you iterate char(8) for each character in the progress updating text before each call to write an update on the progress text.
russo