Dekorateur zur Vermeidung von UnicodeEncodeError in Python 3 print ()

Ich habe es geschrieben, nachdem ich den Dekorateur geübt hatte. Es wurde bestätigt, dass es mit Python 3.3.0 funktioniert.

Da es sich um einen alltäglichen Inhalt handelt, werde ich die Erklärung weglassen, aber standardmäßig

Es ist dafür gedacht.

Es scheint Raum für eine erneute Überprüfung der Spezifikationen zu geben. Wenn Sie also gute Ideen haben, teilen Sie uns dies bitte in den Kommentaren mit. Wir freuen uns auch über Fehler oder schlechte Punkte.

fixprint.py


#!/usr/bin/env python3
# vim:fileencoding=utf-8

# Copyright (c) 2013 Masami HIRATA <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#     1. Redistributions of source code must retain the above copyright notice,
#        this list of conditions and the following disclaimer.
#
#     2. Redistributions in binary form must reproduce the above copyright
#        notice, this list of conditions and the following disclaimer in the
#        documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

__all__ = ["fixprint"]

import codecs
from collections import namedtuple
from functools import partial, wraps
import sys

STREAMS = ("stdin", "stdout", "stderr")
ARGUMENTS = ("encoding", "errors")
ENCODING_DEFAULT = 'utf-8'
ERRORS_DEFAULT = 'backslashreplace'
ENCODING_ASCII = 'ascii'
ENCODING_UTF8 = 'utf-8'
ANY = None


def fixprint(function=None, encoding=None, *, errors=None):
    """This decorator changes the 'encoding' and 'errors' of stdin/out/err

        >>> import sys
        >>> @fixprint(encoding='latin-1', errors='replace')
        ... def spam():
        ...     print("sys.stdout.encoding in spam() is '{}'".format(
        ...           sys.stdout.encoding))
        ...
        >>> @fixprint('utf-8')
        ... def ham():
        ...     spam()
        ...     print("sys.stdout.encoding in ham() is '{}'".format(
        ...           sys.stdout.encoding))
        ...
        >>> ham()  # doctest: +SKIP
        sys.stdout.encoding in spam() is 'latin-1'
        sys.stdout.encoding in ham() is 'utf-8'
        >>>
    """

    if not callable(function):
        if function is not None:
            if encoding is not None:
                # @fixprint("utf-8", encoding="ascii")  # WRONG
                raise TypeError("fixprint() takes 1 positional argument " +
                                "but 2 were given")
            else:
                # @fixprint("utf-8")  # CORRECT
                encoding = function
        return partial(fixprint, encoding=encoding, errors=errors)

    def _setarg(base, stream, argument, value):
        if stream is ANY:
            streams = STREAMS
        else:
            streams = (stream,)

        if argument is ANY:
            arguments = ARGUMENTS
        else:
            arguments = (argument,)

        for a_stream in streams:
            if type(getattr(base, a_stream)) is property:
                setattr(base, a_stream, namedtuple("_Stream", ARGUMENTS))

            for an_argument in arguments:
                setattr(getattr(base, a_stream), an_argument, value)

    def _reopen_stream(old_stream, new_stream):
        old_stream.flush()
        return open(old_stream.fileno(),
                    old_stream.mode,
                    encoding=new_stream.encoding,
                    errors=new_stream.errors,
                    closefd=False)

    @wraps(function)
    def _fixprint(*args, **kwargs):
        saved = namedtuple("_Saved", STREAMS)
        fixed = namedtuple("_Fixed", STREAMS)
        for stream in STREAMS:
            for argument in ARGUMENTS:
                value = getattr(getattr(sys, stream), argument)
                _setarg(saved, stream, argument, value)
                _setarg(fixed, stream, argument, value)

        normalize = lambda encoding: codecs.lookup(encoding).name

        if encoding is not None:
            _setarg(fixed, ANY, "encoding", encoding)
        elif normalize(saved.stdout.encoding) == normalize(ENCODING_ASCII):
            fixed.stdin.encoding = ENCODING_DEFAULT
            fixed.stdout.encoding = fixed.stderr.encoding = ENCODING_DEFAULT

        if errors is not None:
            _setarg(fixed, ANY, "errors", errors)
        elif normalize(fixed.stdout.encoding) != normalize(ENCODING_UTF8):
            _setarg(fixed, ANY, "errors", ERRORS_DEFAULT)

        sys.stdin = _reopen_stream(sys.stdin, fixed.stdin)
        sys.stdout = _reopen_stream(sys.stdout, fixed.stdout)
        sys.stderr = _reopen_stream(sys.stderr, fixed.stderr)

        try:
            result = function(*args, **kwargs)
        finally:
            sys.stdin = _reopen_stream(sys.stdin, saved.stdin)
            sys.stdout = _reopen_stream(sys.stdout, saved.stdout)
            sys.stderr = _reopen_stream(sys.stderr, saved.stderr)

        return result

    return _fixprint

Recommended Posts

Dekorateur zur Vermeidung von UnicodeEncodeError in Python 3 print ()
So löschen Sie stdout in Python
Melden Sie sich auf der Website in Python an
Sprechen mit Python [Text zu Sprache]
Vermeiden Sie KeyError im Python-Wörterbuch
Vermeiden Sie mehrere Schleifen in Python
Wie man in Python entwickelt
Post an Slack in Python
Eine einfache Möglichkeit, mehrere for-Schleifen in Python zu vermeiden
Zeigen Sie Zahlen und Zeichen an, die Variablen im Python-Druck zugewiesen sind
[Python] Wie man PCA mit Python macht
Konvertieren Sie Markdown in Python in PDF
So sammeln Sie Bilder in Python
Python ist UnicodeEncodeError im CodeBox-Docker
Verwendung von SQLite in Python
Im Python-Befehl zeigt Python auf Python3.8
Versuchen Sie, Trace in Python zu berechnen
Wie man MySQL mit Python benutzt
So verpacken Sie C in Python
Verwendung von ChemSpider in Python
6 Möglichkeiten zum Stringen von Objekten in Python
Verwendung von PubChem mit Python
Umgang mit Japanisch mit Python
Eine Alternative zu "Pause" in Python
[Einführung in Python] So geben Sie eine Zeichenfolge in einer Print-Anweisung aus
[Einführung in Python] Wie verwende ich eine Klasse in Python?
Verwenden Sie print in Python2 lambda expression
Vermeiden Sie verschachtelte Schleifen in PHP und Python
Installieren Sie Pyaudio, um Wellen in Python zu spielen
Ich habe versucht, Permutation in Python zu implementieren
Methode zum Erstellen einer Python-Umgebung in Xcode 6
Ich möchte in der Einschlussnotation drucken
Dynamisches Definieren von Variablen in Python
So machen Sie R chartr () in Python
Pin aktuelles Verzeichnis an Skriptverzeichnis in Python
[Itertools.permutations] So löschen Sie eine Sequenz in Python
PUT gzip direkt in S3 in Python
Drucken Sie einfach die in Python verstrichene Zeit in Sekunden
Senden Sie mit Python (Python3) E-Mails an mehrere Empfänger.
Konvertieren Sie die psd-Datei in Python in png
Beispielskript zum Überfüllen von Signalen in Python
Ich habe versucht, PLSA in Python 2 zu implementieren
So setzen Sie die Standardcodierung in Python auf utf-8
So arbeiten Sie mit BigQuery in Python
Lernen Sie das Designmuster "Decorator" mit Python
Melden Sie sich mit Anforderungen in Python bei Slack an
Wie bekomme ich Stacktrace in Python?
So zeigen Sie die neunundneunzig Tabelle in Python an
Einfache Möglichkeit, Wikipedia mit Python zu verwenden
So extrahieren Sie einen Polygonbereich in Python
So überprüfen Sie die Version von opencv mit Python
Ich habe versucht, ADALINE in Python zu implementieren
[Python] Pandas in 10 Minuten vollständig zu verstehen
Werfen Sie Incoming Webhook in Python auf Mattermost
Modul zum Generieren des Wortes N-Gramm in Python
Verweisen auf Umgebungsvariablen in Python in Blender
Ich wollte ABC159 mit Python lösen
Ich habe versucht, PPO in Python zu implementieren
So wechseln Sie die Python-Version in Cloud9