my_hexdump.py

#! /usr/bin/python3
# ===================================================================
# my version of the unix hd command (hd datafile.txt)
# -------------------------------------------------------------------
# Note: there is nothing special about this program. i did
#       it bacause i wanted to. in fact it has less functionallity
#       than "hd".
# ===================================================================

import sys


# -------------------------------------------------------------------
# ---- hexdump a sequence of bytes
# ----
# ---- Base on code from:
# ----     www.geoffreybrown.com/blog/a-hexdump-program-in-python/
# -------------------------------------------------------------------

def hexdump(baddr,bdata):

    # hex string
    s1 = " ".join([f"{i:02x}" for i in bdata])

    # insert extraspace between groups of 8 hex values
    s1 = s1[0:23] + " " + s1[23:]

    # ascii string
    s2 = "".join([chr(i) if 32 <= i <= 127 else "." for i in bdata])

    print(f"{baddr * 16:08x}  {s1:<48}  |{s2}|")


# -------------------------------------------------------------------
# ---- hexdump a file, 16 bytes at a time
# -------------------------------------------------------------------

def hexdump_file(filepath):

    baddr = 0

    with open(filepath,"rb") as f:
        for bdata in iter(lambda: f.read(16), b''):
            hexdump(baddr,bdata)
            baddr += 16


# -------------------------------------------------------------------
# ---- get the file path from the command line
# -------------------------------------------------------------------

def get_file_path():

    l = len(sys.argv)

    if l != 2:
        print()
        print(f'illegal number of arguments on command line ({l})')
        print()
        sys.exit()

    return sys.argv[1]


# -------------------------------------------------------------------
# ---- main
# -------------------------------------------------------------------

if __name__ == '__main__':

    fp = get_file_path()

    hexdump_file(fp)