Skip to content

Commit

Permalink
Stop using sys.__stdout__
Browse files Browse the repository at this point in the history
  • Loading branch information
jiasli committed Jun 19, 2020
1 parent c83997e commit f8a061b
Showing 1 changed file with 11 additions and 10 deletions.
21 changes: 11 additions & 10 deletions knack/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,13 @@ def __init__(self,
# Otherwise, if the downstream command doesn't support color, Knack will fail with
# BrokenPipeError: [Errno 32] Broken pipe, like `az --version | head --lines=1`
# https://github.com/Azure/azure-cli/issues/13413
enable_color_config = not self.config.getboolean('core', 'no_color', fallback=False)
self.enable_color = enable_color_config and isatty(self.out_file) and isatty(sys.stderr)
conditions = (not self.config.getboolean('core', 'no_color', fallback=False),
isatty(sys.stdout), isatty(sys.stderr), self.out_file is sys.stdout)
self.enable_color = all(conditions)
# Delay showing the debug message, as logging is not initialized yet
self.init_debug_log.append("out_file.isatty: {}, stderr.isatty: {}, enable_color_config: {}, enable_color: {}"
.format(isatty(self.out_file), isatty(sys.stderr),
enable_color_config, self.enable_color))
self.init_debug_log.append("enable_color({}) = enable_color_config({}) && "
"stdout.isatty({}) && stderr.isatty({}) && out_file_is_stdout({})"
.format(self.enable_color, *conditions))

@staticmethod
def _should_show_version(args):
Expand Down Expand Up @@ -216,15 +217,14 @@ def invoke(self, args, initial_invocation_data=None, out_file=None):
raise TypeError('args should be a list or tuple.')
exit_code = 0
try:
if self.enable_color:
out_file = out_file or self.out_file
if out_file is sys.stdout and self.enable_color:
import colorama
colorama.init()
if self.out_file == sys.__stdout__:
# point out_file to the new sys.stdout which is overwritten by colorama
self.out_file = sys.stdout
# point out_file to the new sys.stdout which is overwritten by colorama
out_file = sys.stdout

args = self.completion.get_completion_args() or args
out_file = out_file or self.out_file

self.logging.configure(args)
logger.debug('Command arguments: %s', args)
Expand Down Expand Up @@ -261,6 +261,7 @@ def invoke(self, args, initial_invocation_data=None, out_file=None):
self.raise_event(EVENT_CLI_POST_EXECUTE)

if self.enable_color:
import colorama
colorama.deinit()

return exit_code

0 comments on commit f8a061b

Please sign in to comment.