1import binascii 2import shlex 3import subprocess 4 5def get_command_output(command): 6 try: 7 return subprocess.check_output( 8 command, 9 shell=True, 10 universal_newlines=True).rstrip() 11 except subprocess.CalledProcessError as e: 12 return e.output 13 14def bitcast_to_string(b: bytes) -> str: 15 """ 16 Take a bytes object and return a string. The returned string contains the 17 exact same bytes as the input object. (latin1 <-> unicode transformation is 18 an identity operation for the first 256 code points). 19 """ 20 return b.decode("latin1") 21 22def bitcast_to_bytes(s: str) -> bytes: 23 """ 24 Take a string and return a bytes object. The returned object contains the 25 exact same bytes as the input string. (latin1 <-> unicode transformation isi 26 an identity operation for the first 256 code points). 27 """ 28 return s.encode("latin1") 29 30def unhexlify(hexstr): 31 """Hex-decode a string. The result is always a string.""" 32 return bitcast_to_string(binascii.unhexlify(hexstr)) 33 34def hexlify(data): 35 """Hex-encode string data. The result if always a string.""" 36 return bitcast_to_string(binascii.hexlify(bitcast_to_bytes(data))) 37 38# TODO: Replace this with `shlex.join` when minimum Python version is >= 3.8 39def join_for_shell(split_command): 40 return " ".join([shlex.quote(part) for part in split_command]) 41