Robot Framework
encoding.py
Go to the documentation of this file.
1 # Copyright 2008-2015 Nokia Networks
2 # Copyright 2016- Robot Framework Foundation
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 import os
17 import sys
18 
19 from .encodingsniffer import get_console_encoding, get_system_encoding
20 from .misc import isatty
21 from .robottypes import is_string
22 from .unic import safe_str
23 
24 
25 CONSOLE_ENCODING = get_console_encoding()
26 SYSTEM_ENCODING = get_system_encoding()
27 PYTHONIOENCODING = os.getenv('PYTHONIOENCODING')
28 
29 
30 
39 def console_decode(string, encoding=CONSOLE_ENCODING):
40  if is_string(string):
41  return string
42  encoding = {'CONSOLE': CONSOLE_ENCODING,
43  'SYSTEM': SYSTEM_ENCODING}.get(encoding.upper(), encoding)
44  try:
45  return string.decode(encoding)
46  except UnicodeError:
47  return safe_str(string)
48 
49 
50 
60 def console_encode(string, encoding=None, errors='replace', stream=sys.__stdout__,
61  force=False):
62  if encoding:
63  encoding = {'CONSOLE': CONSOLE_ENCODING,
64  'SYSTEM': SYSTEM_ENCODING}.get(encoding.upper(), encoding)
65  else:
66  encoding = _get_console_encoding(stream)
67  if encoding != 'UTF-8':
68  encoded = string.encode(encoding, errors)
69  return encoded if force else encoded.decode(encoding)
70  return string.encode(encoding, errors) if force else string
71 
72 
74  encoding = getattr(stream, 'encoding', None)
75  if isatty(stream):
76  return encoding or CONSOLE_ENCODING
77  if PYTHONIOENCODING:
78  return PYTHONIOENCODING
79  return encoding or SYSTEM_ENCODING
80 
81 
82 def system_decode(string):
83  return string if is_string(string) else safe_str(string)
84 
85 
86 def system_encode(string):
87  return string if is_string(string) else safe_str(string)
def console_decode(string, encoding=CONSOLE_ENCODING)
Decodes bytes from console encoding to Unicode.
Definition: encoding.py:39
def system_encode(string)
Definition: encoding.py:86
def system_decode(string)
Definition: encoding.py:82
def _get_console_encoding(stream)
Definition: encoding.py:73
def console_encode(string, encoding=None, errors='replace', stream=sys.__stdout__, force=False)
Encodes the given string so that it can be used in the console.
Definition: encoding.py:61
def isatty(stream)
Definition: misc.py:116
def safe_str(item)
Definition: unic.py:21