Search code examples
pythonandroidandroid-emulatorsubprocessadb

Running adb reboot command from python


Running the adb reboot command from code always produces an error. In fact, the device reboots and when adb reboot commend run directly from terminal everything is ok, but I don't know how to handle this correctly in python code (unfortunately all chat GPTt suggestions fail). Probably the connection is lost when rebooting and then error is returned...

Do you have any suggestions or do you know how to handle it?

Full code:

import subprocess


def execute_adb(adb_command):
    # print(adb_command)
    result = subprocess.run(
        adb_command,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )
    if result.returncode == 0:
        return result.stdout.strip()
    print(f"returncode {result.returncode}, stderr: {result.stderr.lower()}, stdout: {result.stdout}")
    return "ERROR"

class AndroidController:
    def __init__(self, device):
        self.device = device

    def is_device_online(self):
        adb_command = f"adb -s {self.device} get-state"
        result = execute_adb(adb_command)
        return result == "device"

    def reset_device(self):
        adb_command = f"adb -s {self.device} shell reboot"
        ret = execute_adb(adb_command)
        return ret

controller = AndroidController("emulator-5554")
print(controller.is_device_online())
controller.reset_device()

Output:

True
returncode 255, stderr: , stdout: 

Process finished with exit code 0

Solution

  • As mentioned by @Robert in the comments the proper way is adb reboot. Both commands will do it but the return code is different, and that's another reason to use this one.

    >>> subprocess.run(['adb', 'reboot'])
    CompletedProcess(args=['adb', 'reboot'], returncode=0)
    >>> subprocess.run(['adb', 'shell', 'reboot'])
    CompletedProcess(args=['adb', 'shell', 'reboot'], returncode=255)