MythTV master
util.py
Go to the documentation of this file.
1# This file is part of the musicbrainzngs library
2# Copyright (C) Alastair Porter, Adrian Sampson, and others
3# This file is distributed under a BSD-2-Clause type license.
4# See the COPYING file for more information.
5
6import sys
7import locale
8import xml.etree.ElementTree as ET
9
10from . import compat
11
12def _unicode(string, encoding=None):
13 """Try to decode byte strings to unicode.
14 This can only be a guess, but this might be better than failing.
15 It is safe to use this on numbers or strings that are already unicode.
16 """
17 if isinstance(string, compat.unicode):
18 unicode_string = string
19 elif isinstance(string, compat.bytes):
20 # use given encoding, stdin, preferred until something is not None is found
21 if encoding is None:
22 encoding = sys.stdin.encoding
23 if encoding is None:
24 encoding = locale.getpreferredencoding()
25 unicode_string = string.decode(encoding, "ignore")
26 else:
27 unicode_string = compat.unicode(string)
28 return unicode_string.replace('\x00', '').strip()
29
30def bytes_to_elementtree(bytes_or_file):
31 """Given a bytestring or a file-like object that will produce them,
32 parse and return an ElementTree.
33 """
34 if isinstance(bytes_or_file, compat.basestring):
35 s = bytes_or_file
36 else:
37 s = bytes_or_file.read()
38
39 if compat.is_py3:
40 s = _unicode(s, "utf-8")
41
42 f = compat.StringIO(s)
43 tree = ET.ElementTree(file=f)
44 return tree
def _unicode(string, encoding=None)
Definition: util.py:12
def bytes_to_elementtree(bytes_or_file)
Definition: util.py:30