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