codekingpro/portable-devtools
114k
1"""
2"""
3
4# Created on 2015.07.09
5#
6# Author: Giovanni Cannata
7#
8# Copyright 2015 - 2020 Giovanni Cannata
9#
10# This file is part of ldap3.
11#
12# ldap3 is free software: you can redistribute it and/or modify
13# it under the terms of the GNU Lesser General Public License as published
14# by the Free Software Foundation, either version 3 of the License, or
15# (at your option) any later version.
16#
17# ldap3 is distributed in the hope that it will be useful,
18# but WITHOUT ANY WARRANTY; without even the implied warranty of
19# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20# GNU Lesser General Public License for more details.
21#
22# You should have received a copy of the GNU Lesser General Public License
23# along with ldap3 in the COPYING and COPYING.LESSER files.
24# If not, see <http://www.gnu.org/licenses/>.
25from binascii import hexlify
26
27from .. import STRING_TYPES
28
29try:
30 from sys import stdout
31 repr_encoding = stdout.encoding # get the encoding of the stdout for printing (repr)
32 if not repr_encoding:
33 repr_encoding = 'ascii' # default
34except Exception:
35 repr_encoding = 'ascii' # default
36
37
38def to_stdout_encoding(value):
39 if not isinstance(value, STRING_TYPES):
40 value = str(value)
41
42 if str is bytes: # Python 2
43 try:
44 return value.encode(repr_encoding, 'backslashreplace')
45 except UnicodeDecodeError: # Python 2.6
46 return hexlify(value)
47 else: # Python 3
48 try:
49 return value.encode(repr_encoding, errors='backslashreplace').decode(repr_encoding, errors='backslashreplace')
50 except UnicodeDecodeError:
51 return hexlify(value)
52 