From 27bd4c5570ead2df48371080f4ad3d2de46df3e6 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 8 Jun 2016 09:51:29 -0700 Subject: [PATCH] Fix #2041: encoding detection when stdin is a pipe --- beets/ui/__init__.py | 27 ++++++++++++++++----------- docs/changelog.rst | 2 ++ 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 39a046fba..a2739189e 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -73,32 +73,37 @@ class UserError(Exception): # Encoding utilities. -def _in_encoding(default=u'utf-8'): +def _in_encoding(): """Get the encoding to use for *inputting* strings from the console. - - :param default: the fallback sys.stdin encoding """ - - return config['terminal_encoding'].get() or getattr(sys.stdin, 'encoding', - default) + return _stream_encoding(sys.stdin) def _out_encoding(): """Get the encoding to use for *outputting* strings to the console. """ + return _stream_encoding(sys.stdout) + + +def _stream_encoding(stream, default='utf8'): + """A helper for `_in_encoding` and `_out_encoding`: get the stream's + preferred encoding, using a configured override or a default + fallback if neither is not specified. + """ # Configured override? encoding = config['terminal_encoding'].get() if encoding: return encoding - # For testing: When sys.stdout is a StringIO under the test harness, - # it doesn't have an `encoding` attribute. Just use UTF-8. - if not hasattr(sys.stdout, 'encoding'): - return 'utf8' + # For testing: When sys.stdout or sys.stdin is a StringIO under the + # test harness, it doesn't have an `encoding` attribute. Just use + # UTF-8. + if not hasattr(stream, 'encoding'): + return default # Python's guessed output stream encoding, or UTF-8 as a fallback # (e.g., when piped to a file). - return sys.stdout.encoding or 'utf8' + return stream.encoding or default def _arg_encoding(): diff --git a/docs/changelog.rst b/docs/changelog.rst index 6fc835c61..2596a8ba5 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -23,6 +23,8 @@ Fixes: tried to enable the Google lyrics source. * Fix a hard-coded path to ``bash-completion`` to work better with Homebrew installations. Thanks to :user:`bismark`. :bug:`2038` +* Fix a crash introduced in the previous version when the standard input was + connected to a Unix pipe. :bug:`2041` 1.3.18 (May 31, 2016)