Skip to content

Commit

Permalink
Fixing encoding error when redirecting stdout/err to a file (#210)
Browse files Browse the repository at this point in the history
  • Loading branch information
mindstorm38 committed Apr 16, 2024
1 parent 2788b1c commit 07c4e27
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
8 changes: 8 additions & 0 deletions portablemc/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from pathlib import Path
import socket
import sys
import io

from .parse import register_arguments, RootNs, SearchNs, StartNs, LoginNs, LogoutNs, AuthBaseNs, ShowCompletionNs

Expand Down Expand Up @@ -67,6 +68,13 @@ def main(args: Optional[List[str]] = None):
`get_command_handlers` function.
"""

# Force stdout/stderr to use UTF-8 encoding, this reconfigure method
# is available for Python 3.7 and onward.
if isinstance(sys.stdout, io.TextIOWrapper):
sys.stdout.reconfigure(encoding='utf-8')
if isinstance(sys.stderr, io.TextIOWrapper):
sys.stderr.reconfigure(encoding='utf-8')

parser = register_arguments()
ns: RootNs = cast(RootNs, parser.parse_args(args or sys.argv[1:]))

Expand Down
6 changes: 3 additions & 3 deletions portablemc/cli/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,10 @@ def print(self, text: str) -> None:
break

if chosen_color is not None:
print(chosen_color, text, "\033[0m", sep="", end="")
print(chosen_color, text, "\033[0m", sep="", end="", flush=True)
return

print(text, end="")
print(text, end="", flush=True)

def prompt(self, password: bool = False) -> Optional[str]:
try:
Expand Down Expand Up @@ -247,7 +247,7 @@ def print(self) -> None:

print(format_string.format(*format_columns), flush=False)

print("└─{}─┘".format("─┴─".join(columns_lines)))
print("└─{}─┘".format("─┴─".join(columns_lines)), flush=True)


class MachineOutput(Output):
Expand Down

0 comments on commit 07c4e27

Please sign in to comment.