How to call command via ADB on android device using python?

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To call a command via ADB (Android Debug Bridge) on an Android device using Python, you can use the subprocess module in Python to execute ADB commands. Here's an example:

python
import subprocess

def adb_shell(command):
adb_command = f'adb shell {command}'
result = subprocess.run(adb_command, capture_output=True, text=True, shell=True)
if result.returncode == 0:
return result.stdout.strip()
else:
return result.stderr.strip()

# Example usage
output = adb_shell('ls /sdcard')
print(output)

In this example, the adb_shell function takes an ADB command as an argument, executes it using subprocess.run, and returns the output of the command as a string. The capture_output=True parameter captures the command's output, and text=True ensures the output is returned as a string. The shell=True parameter allows the command to be executed in a shell environment.

You can then call the adb_shell function with the desired ADB command as an argument. In the example, it executes the ls /sdcard command on the Android device and prints the output.

Make sure you have ADB installed on your computer and that your Android device is connected and recognized by ADB before running the Python script.