Use native text encoding on terminals incapable of UTF-8/UTF-16

This commit is contained in:
Fierelier 2023-05-07 14:01:00 +02:00
parent 50147c60d0
commit 4e4820a85e

View File

@ -1,3 +1,4 @@
import sys
import os import os
import json import json
import logging import logging
@ -9,8 +10,11 @@ import threading
import queue import queue
import platform import platform
if platform.system().startswith("Windows"): if platform.system().startswith("Windows"):
try:
import win_unicode_console import win_unicode_console
win_unicode_console.enable() win_unicode_console.enable()
except Exception as e:
print("Warning: Enabling win_unicode_console failed (" +str(e)+ "), using native encoding.")
from collections import OrderedDict from collections import OrderedDict
from colorama import Fore, Back, Style, init as colorama_init, ansi as colorama_ansi from colorama import Fore, Back, Style, init as colorama_init, ansi as colorama_ansi
@ -44,6 +48,9 @@ commands = OrderedDict([
]) ])
def main(config,context): def main(config,context):
if not "utf" in sys.stdout.encoding.lower(): # Terminal is neither UTF-8 or UTF-16
global print
print = renPrint
logging.info("Testing connection to API at " + config["api"]) logging.info("Testing connection to API at " + config["api"])
logging.debug(json.dumps(context.api_status(), indent = 2)) logging.debug(json.dumps(context.api_status(), indent = 2))
@ -187,6 +194,15 @@ def ws_onmessage(ws, message):
ws.ignored[result["type"]] += 1 ws.ignored[result["type"]] += 1
# print() wrap for terminals incapable of UTF-8/UTF-16
originalPrint = print
def renPrint(*args,**kwargs):
args = list(args)
for index,arg in enumerate(args):
args[index] = arg.encode(sys.stdout.encoding,errors="replace").decode(sys.stdout.encoding)
originalPrint(*args,**kwargs)
# Produce the string output for a given message. Can be printed directly to console # Produce the string output for a given message. Can be printed directly to console
def get_message_string(ws, message, user): def get_message_string(ws, message, user):
result = (MSGPREFIX + Fore.CYAN + Style.BRIGHT + user["username"] + " " + Style.DIM + "#%d" % user["id"] + result = (MSGPREFIX + Fore.CYAN + Style.BRIGHT + user["username"] + " " + Style.DIM + "#%d" % user["id"] +