TencentCloud / tencentcloud-sdk-python

Tencent Cloud API 3.0 SDK for Python
Apache License 2.0
613 stars 251 forks source link

exception cannot be printed when unicode envolved in py2 #15

Closed zqfan closed 5 years ago

zqfan commented 6 years ago

Traceback (most recent call last): File "transmit_oral_process.py", line 42, in print(err) UnicodeEncodeError: 'ascii' codec can't encode characters in position 74-82: ordinal not in range(128)

zqfan commented 6 years ago

only python2 has this problem, instead of print(err), using print("%s" % err) as a workaround for python2, https://stackoverflow.com/questions/1307014/python-str-versus-unicode is another fix, but it is not compatible for python3 http://kmike.ru/python-with-strings-attached/ introduces a compatible way but it seems a bit complicated python2 has a numerous users, but python3 is the future

zqfan commented 6 years ago

a posible fix in py2:

    def __str__(self):
        s = "[TencentCloudSDKException] code:%s message:%s requestId:%s" % (
                self.code, self.message, self.requestId)
        if sys.version_info[0] < 3:
            return s.encode("utf8")
        else:
            return s
zqfan commented 6 years ago

see python bug: https://bugs.python.org/issue2517

zqfan commented 6 years ago

the workaround print("%s" % err) depends on sys.stdout.encoding, you can use export PYTHONIOENCODING="utf-8" to set it to utf8 eventually, it seems we should handle this problem in sdk itself instead of asking user to set environment and use workarounds

zqfan commented 5 years ago

we must test if actions return message with encoded utf bytes, or raw unicode bytes