Screenshotting ADB using Python

820 views Asked by At

so I am trying to screenshot adb and handle it purely from Python hence there will be no files saved on the users device.

I created the following helper functions in order to do so

def adb_run(command, verbose=False):
    result = subprocess.run([r"D:\Program Files\Nox\bin\adb.exe"] + command, stdout=subprocess.PIPE, errors="ignore")
    if verbose:
        print(result.stdout)
    return result


def shell(command, verbose=False):
    return adb_run(['shell', command], verbose)


def screencap():
    return shell(f"screencap -p")

I then called the screencap() function and wrote it to a file, the content seems to be a valid PNG file, but I am not able to load the png file since it says it's corrupted

capped = screencap().stdout
with open("screencap.png", "wb") as f:
    f.write(capped.encode())

Does anyone know why the image file would be corrupted? I haven't found any pure python solutions online

1

There are 1 answers

1
Dan Harms On BEST ANSWER

Try using exec-out rather than shell.

def screencap(filename):
    return adb_run(['exec-out', f'screencap -p > {filename}'])