diff options
author | Martin Braun <martin.braun@ettus.com> | 2017-12-05 16:17:08 -0800 |
---|---|---|
committer | Martin Braun <martin.braun@ettus.com> | 2017-12-22 15:05:57 -0800 |
commit | 06f6156f85cb11ff40e3abc0fa77eba388789a37 (patch) | |
tree | 551ac21c81ebde13bba8f8a2cd0ff76b2dac474e /mpm/python/usrp_mpm/mpmutils.py | |
parent | 73334b188a3efb94ae156df5d0c0f0df02b2583e (diff) | |
download | uhd-06f6156f85cb11ff40e3abc0fa77eba388789a37.tar.gz uhd-06f6156f85cb11ff40e3abc0fa77eba388789a37.tar.bz2 uhd-06f6156f85cb11ff40e3abc0fa77eba388789a37.zip |
mpm: utils: Add string conversion utilities
Adds conversions for:
- Any-to-binary
- Any-to-UTF8
- Any-to-native
Diffstat (limited to 'mpm/python/usrp_mpm/mpmutils.py')
-rw-r--r-- | mpm/python/usrp_mpm/mpmutils.py | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/mpm/python/usrp_mpm/mpmutils.py b/mpm/python/usrp_mpm/mpmutils.py index ad4457419..64474d3ff 100644 --- a/mpm/python/usrp_mpm/mpmutils.py +++ b/mpm/python/usrp_mpm/mpmutils.py @@ -8,6 +8,7 @@ Miscellaneous utilities for MPM """ import time +import sys def poll_with_timeout(state_check, timeout_ms, interval_ms): """ @@ -36,3 +37,44 @@ def poll_with_timeout(state_check, timeout_ms, interval_ms): time.sleep(interval_s) return False +def to_native_str(str_or_bstr): + """ + Returns a native string, regardless of the input string type (binary or + UTF-8), and the Python version (2 or 3). + Note that the native string type is actually not the same in Python 2 and + 3: In the former, it's a binary string, in the latter, it's Unicode. + >>> to_native_str(b'foo') + 'foo' + >>> to_native_str(u'foo') + 'foo' + """ + if isinstance(str_or_bstr, str): + return str_or_bstr + if sys.version_info.major >= 3: + return str(str_or_bstr, encoding='ascii') + else: + return str(str_or_bstr) + +def to_binary_str(str_or_bstr): + """ + Returns a binary string, regardless of the input string type (binary or + UTF-8), and the Python version (2 or 3). + Note that in Python 2, a binary string is the native string type. + """ + try: + return bytes(str_or_bstr.encode('utf-8')) + except AttributeError: + return bytes(str_or_bstr) + + +def to_utf8_str(str_or_bstr): + """ + Returns a unicode string, regardless of the input string type (binary or + UTF-8), and the Python version (2 or 3). + Note that in Python 2, a unicode string is not the native string type. + """ + try: + return str_or_bstr.decode('utf-8') + except AttributeError: + return str_or_bstr + |