使用特殊 Unicode 类解决方案刷新 Windows 控制台屏幕

0 投票
1 回答
624 浏览
提问于 2025-04-16 03:22

我正在尝试在Windows控制台中制作一个简单的文本进度条,并且还想显示UTF-8字符。

问题不是Unicode字符无法显示,它们是可以显示的。问题在于,为了让Unicode字符显示,我使用了一个类来告诉系统输出该怎么做。这影响了正常的flush()功能。

我该如何在控制台中恢复这个flush()功能,同时又能使用这个Unicode类呢?

#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')

1 个回答

1

也许你可以试试用更简单的方法,就是用退格键来删除之前的数字?

或者可以做一些类似这样的操作:

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

在回车后用空格覆盖,然后再回车一次。

我在这样做的时候没有看到任何闪烁的情况,这个方法对我来说只有在从命令窗口运行代码时有效,而不是双击运行。

#<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')

撰写回答