A
A
Alexey Yarkov2015-11-14 14:50:08
Python
Alexey Yarkov, 2015-11-14 14:50:08

How to defeat encodings in Python?

Good afternoon. We have a script in utf-8 encoding. It dynamically loads plugins. We have the property __charset = 'utf-8' in the class by default. When initializing the class, if the encoding argument is not None, then we change self.__charset = 'utf-8' to self.__charset = encoding. Something like that:

def __init__(self, path = None, encoding = None):
    if not encoding is None:
      self.__charset = encoding
      reload(sys)
      sys.setdefaultencoding(self.__charset)
      sys.stdout = codecs.getwriter(self.__charset)(sys.stdout)
      print self.__charset

So if you run the script by clicking, then we have utf-8 encoding and Cyrillic is displayed normally. But if you run it from the command line, then the encoding is cp866 (pass it to the constructor) and the Cyrillic alphabet is displayed in shorthand. I don't know what else can be done.
if len(sys.argv) > 1:
  print "The program is run from the console."
  print "Most likely there will be problems with the encoding of messages output, since the script was written in utf-8 encoding."
  continued = raw_input("Do you want to continue? Y/N ")
  if continued and continued.upper() == 'Y':
    grunt = PyGrunt(sys.argv[1], encoding = 'cp866')

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2015-11-14
@yarkov

Use python3

G
gimntut, 2015-11-14
@gimntut

Decision

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question