10af864b4SPavel Labathimport binascii 2b42d51baSPavel Labathimport shlex 39dbf62f9SZachary Turnerimport subprocess 49dbf62f9SZachary Turner 5*2238dcc3SJonas Devlieghere 69dbf62f9SZachary Turnerdef get_command_output(command): 756f9cfe3SDave Lee try: 856f9cfe3SDave Lee return subprocess.check_output( 9*2238dcc3SJonas Devlieghere command, shell=True, universal_newlines=True 10*2238dcc3SJonas Devlieghere ).rstrip() 1156f9cfe3SDave Lee except subprocess.CalledProcessError as e: 1256f9cfe3SDave Lee return e.output 13bac6e4f7SZachary Turner 14*2238dcc3SJonas Devlieghere 1556f9cfe3SDave Leedef bitcast_to_string(b: bytes) -> str: 1656f9cfe3SDave Lee """ 1756f9cfe3SDave Lee Take a bytes object and return a string. The returned string contains the 1856f9cfe3SDave Lee exact same bytes as the input object. (latin1 <-> unicode transformation is 1956f9cfe3SDave Lee an identity operation for the first 256 code points). 2056f9cfe3SDave Lee """ 2156f9cfe3SDave Lee return b.decode("latin1") 220af864b4SPavel Labath 23*2238dcc3SJonas Devlieghere 2456f9cfe3SDave Leedef bitcast_to_bytes(s: str) -> bytes: 250af864b4SPavel Labath """ 2656f9cfe3SDave Lee Take a string and return a bytes object. The returned object contains the 2756f9cfe3SDave Lee exact same bytes as the input string. (latin1 <-> unicode transformation isi 2856f9cfe3SDave Lee an identity operation for the first 256 code points). 290af864b4SPavel Labath """ 3056f9cfe3SDave Lee return s.encode("latin1") 310af864b4SPavel Labath 32*2238dcc3SJonas Devlieghere 330af864b4SPavel Labathdef unhexlify(hexstr): 340af864b4SPavel Labath """Hex-decode a string. The result is always a string.""" 350af864b4SPavel Labath return bitcast_to_string(binascii.unhexlify(hexstr)) 360af864b4SPavel Labath 37*2238dcc3SJonas Devlieghere 380af864b4SPavel Labathdef hexlify(data): 390af864b4SPavel Labath """Hex-encode string data. The result if always a string.""" 400af864b4SPavel Labath return bitcast_to_string(binascii.hexlify(bitcast_to_bytes(data))) 41b42d51baSPavel Labath 42*2238dcc3SJonas Devlieghere 43b42d51baSPavel Labath# TODO: Replace this with `shlex.join` when minimum Python version is >= 3.8 44b42d51baSPavel Labathdef join_for_shell(split_command): 45b42d51baSPavel Labath return " ".join([shlex.quote(part) for part in split_command]) 46