tylko myślałem, że dodam mój pomysł ...odpowiadał moim celom, aby móc uruchomić sthg w Eclipse, a następnie uruchomić z CLI (Windows) bez uzyskiwania wyjątków kodowania z każdym poleceniem print. Cokolwiek robisz, nie czynisz klasy EncodingStdout podklasą pliku klasy: wiersz "self.encoding = encoding" spowodowałby, że atrybut encoding był None!
NB Jedną rzeczą, którą dowiedziałem się w ciągu dnia, zmagając się z tym problemem jest to, że wyjątek kodowania zostaje podniesiony PRZED uzyskaniem "drukowania" lub "zapisu": to jest, gdy sparametryzowany ciąg znaków (np. "Mondodod% s blah blah%" s "% (" blip "," blap ")) jest zbudowany przez ... co ??? ramy"?
class EncodingStdout(object):
def __init__(self, encoding='utf-8'):
self.encoding = encoding
def write_ln(self, *args):
if len(args) < 2:
sys.__stdout__.write(args[ 0 ] + '\n')
else:
if not isinstance(args[ 0 ], basestring):
raise Exception("first arg was %s, type %s" % (args[ 0 ], type(args[ 0 ])))
# if the default encoding is UTF-8 don't bother with encoding
if sys.getdefaultencoding() != 'utf-8':
encoded_args = [ args[ 0 ] ]
for i in range(1, len(args)):
# numbers (for example) do not have an attribute "encode"
if hasattr(args[ i ], 'encode'):
encoded_args.append(args[ i ].encode(self.encoding, 'replace'))
else:
encoded_args.append(args[ i ])
args = encoded_args
sys.__stdout__.write(args[ 0 ] % tuple(args[ 1 : ]) + '\n')
# write seems to need a flush
sys.__stdout__.flush()
def __getattr__(self, name):
return sys.__stdout__.__getattribute__(name)
print "=== A mondodod %s %s" % ("été", "pluviôse, irritée contre la ville entière")
sys.stdout = EncodingStdout()
sys.stdout.write_ln("=== B mondodod %s %s", "été", "pluviôse, irritée contre la ville entière")
# convenience method
def pr(*args):
sys.stdout.write_ln(*args)
pr("=== C mondodod %s %s", "été", "pluviôse, irritée contre la ville entière")
'saved = sys.stdout' jest niepotrzebne,' sys .__ stdout__' zawsze zawiera oryginalne 'stdout', więc na końcu wystarczy' sys.stdout = sys .__ stdout__'. – chown
zapisywanie sys.stdout umożliwia przesłonięcie łańcucha; jeśli napiszesz bezpośrednio do sys .__ stdout__ pominiesz jakiekolwiek struktury logowania lub takie, które spróbujesz i wstrzykniesz do programu. Najlepiej jawnie zapisać poprzednią wartość stdout. – Will
Czy istnieje szczególny powód, dla którego otwierasz dziennik za pomocą 'file()' zamiast 'open()'? [Dokumentacja tego zaleca.] (Https://docs.python.org/2/library/functions.html#file) – Eric