python编码在控制台outpu中返回

2022-05-21 08:46:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下功能:

def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█'):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - cOptional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
    """
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\r')
    # Print New Line on Complete
    if iteration == total: 
        print()

这给了我下面的错误:

Traceback (most recent call last):---------------------------| 2.0% Complete
  File "script.py", line 75, in <module>
    printProgressBar(count + 1, len(df), prefix = 'Progress:', suffix = 'Complete', length = 50)
  File "script.py", line 36, in printProgressBar
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\r')
UnicodeEncodeError: 'ascii' codec can't encode character '\u2588' in position 12: ordinal not in range(128)

我相信是编码错误。。。但我不知道如何解决它。其他问题建议使用.encode(),但在我的情况下,我不确定在哪里可以使用字符串转换。感谢您的帮助


Tags: inprefixbarfilllengthsuffixoptionalinttotalpercentcharacterstriterationdecimalsprintprogressbar