We plan to use python to control android phone. In this tutorial, we will tell you how to capture android phone screenshot using python and adb.
Capture android phone screenshot using adb
We can use adb command to capture screenshot.
Here is the command:
adb shell screencap -p
However, if you want to use python get run adb command and save screenshot to an image file. How to do?
Capture android phone screenshot using adb and python
Here we write an example to show you how to do.
import subprocess import os import sys def get_screen(filename): cmd = "adb shell screencap -p" process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) binary_screenshot = process.stdout.read() binary_screenshot = binary_screenshot.replace(b'\r\r\n', b'\n') with open(filename,'wb') as f: f.write(binary_screenshot) get_screen(filename='phone.png')
In this example, we will use subprocess.Popen() to run adb command and get the data of android phone screenshot.
Then we will save image data to png file.
You should notice: binary_screenshot cotains the screenshot data, the type of it is byte.
Run this python code, this code will save phone screenshot to phone.png file.