mozdevice — Interact with Android devices

mozdevice provides a Python interface to the Android Debug Bridge (adb) for Android Devices.

mozdevice exports the following classes:

ADBProcess is a class which is used by ADBCommand to execute commands via subprocess.Popen.

ADBCommand is an internal only class which provides the basics of the interfaces for connecting to a device, and executing commands either on the host or device using ADBProcess.

ADBHost is a Python class used to execute commands which are not necessarily associated with a specific device. It is intended to be used directly.

ADBDevice is a Python class used to execute commands which will interact with a specific connected Android device.

ADBAndroid inherits directly from ADBDevice and is essentially a synonym for ADBDevice. It is included for backwards compatibility only and should not be used in new code.

ADBDeviceFactory is a Python function used to create instances of ADBDevice. ADBDeviceFactory is preferred over using ADBDevice to create new instances of ADBDevice since it will only create one instance of ADBDevice for each connected device.

mozdevice exports the following exceptions:

Exception -
|- ADBTimeoutError
|- ADBDeviceFactoryError
|- ADBError
   |- ADBProcessError
   |- ADBListDevicesError

ADBTimeoutError is a special exception that is not part of the ADBError class hierarchy. It is raised when a command has failed to complete within the specified timeout period. Since this typically is due to a failure in the usb connection to the device and is not recoverable, it is implemented separately from ADBError so that it will not be caught by normal except clause handling of expected error conditions and is considered to be treated as a fatal error.

ADBDeviceFactoryError is also a special exception that is not part of the ADBError class hierarchy. It is raised by ADBDeviceFactory when the state of the internal ADBDevices object is in an inconsistent state and is considered to be a fatal error.

ADBListDevicesError is an instance of ADBError which is raised only by the ADBHost.devices() method to signify that adb devices reports that the device state has no permissions and can not be contacted via adb.

ADBProcessError is an instance of ADBError which is raised when a process executed via ADBProcess has exited with a non-zero exit code. It is raised by the ADBCommand.command method and the methods that call it.

ADBError is a generic exception class to signify that some error condition has occured which may be handled depending on the semantics of the executing code.

Example:

from mozdevice import ADBHost, ADBDeviceFactory, ADBError

adbhost = ADBHost()
try:
    adbhost.kill_server()
    adbhost.start_server()
except ADBError as e:
    print('Unable to restart the adb server: {}'.format(str(e)))

device = ADBDeviceFactory()
try:
    sdcard_contents = device.ls('/sdcard/')  # List the contents of the sdcard on the device.
    print('sdcard contains {}'.format(' '.join(sdcard_contents))
except ADBError as e:
    print('Unable to list the sdcard: {}'.format(str(e)))

Android devices use a security model based upon user permissions much like that used in Linux upon which it is based. The adb shell executes commands on the device as the shell user whose access to the files and directories on the device are limited by the directory and file permissions set in the device’s file system.

Android apps run under their own user accounts and are restricted by the app’s requested permissions in terms of what commands and files and directories they may access.

Like Linux, Android supports a root user who has unrestricted access to the command and content stored on the device.

Most commercially released Android devices do not allow adb to run commands as the root user. Typically, only Android emulators running certain system images, devices which have AOSP debug or engineering Android builds or devices which have been rooted can run commands as the root user.

ADBDevice supports using both unrooted and rooted devices by laddering its capabilities depending on the specific circumstances where it is used.

ADBDevice uses a special location on the device, called the test_root, where it places content to be tested. This can include binary executables and libraries, configuration files and log files. Since the special location /data/local/tmp is usually accessible by the shell user, the test_root is located at /data/local/tmp/test_root by default. /data/local/tmp is used instead of the sdcard due to recent Scoped Storage restrictions on access to the sdcard in Android 10 and later.

If the device supports running adbd as root, or if the device has been rooted and supports the use of the su command to run commands as root, ADBDevice will default to running all shell commands under the root user and the test_root will remain set to /data/local/tmp/test_root unless changed.

If the device does not support running shell commands under the root user, and a debuggable app is set in ADBDevice property run_as_package, then ADBDevice will set the test_root to /data/data/<app-package-name>/test_root and will run shell commands as the app user when accessing content located in the app’s data directory. Content can be pushed to the app’s data directory or pulled from the app’s data directory by using the command run-as to access the app’s data.

If a device does not support running commands as root and a debuggable app is not being used, command line programs can still be executed by pushing them to the /data/local/tmp directory which is accessible to the shell user.

If for some reason, the device is not rooted and /data/local/tmp is not acccessible to the shell user, then ADBDevice will fail to initialize and will not be useable for that device.

NOTE: ADBFactory will clear the contents of the test_root when it first creates an instance of ADBDevice.

When the run_as_package property is set in an ADBDevice instance, it will clear the contents of the current test_root before changing the test_root to point to the new location /data/data/<app-package-name>/test_root which will then be cleared of any existing content.

class mozdevice.ADBAndroid(device=None, adb='adb', adb_host=None, adb_port=None, test_root=None, logger_name='adb', timeout=300, verbose=False, device_ready_retry_wait=20, device_ready_retry_attempts=3, use_root=True, share_test_root=True, run_as_package=None)

Bases: mozdevice.adb.ADBDevice

ADBAndroid functionality is now provided by ADBDevice. New callers should use ADBDevice.

SOCKET_DIRECTION_FORWARD = 'forward'
SOCKET_DIRECTION_REVERSE = 'reverse'
batch_execute(commands, timeout=None, enable_run_as=False)

Writes commands to a temporary file then executes on the device.

Parameters
  • commands_list (list) – List of commands to be run by the shell.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • enable_run_as (bool) – Flag used to temporarily enable use of run-as to execute the command.

Raises

ADBTimeoutError ADBError

chmod(path, recursive=False, mask='777', timeout=None)

Recursively changes the permissions of a directory on the device.

Parameters
  • path (str) – The directory name on the device.

  • recursive (bool) – Flag specifying if the command should be executed recursively.

  • mask (str) – The octal permissions.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

chown(path, owner, group=None, recursive=False, timeout=None)

Run the chown command on the provided path.

Parameters
  • path (str) – path name on the device.

  • owner (str) – new owner of the path.

  • group (str) – optional parameter specifying the new group the path should belong to.

  • recursive (bool) – optional value specifying whether the command should operate on files and directories recursively.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

clear_logcat(timeout=None, buffers=[])

Clears logcat via adb logcat -c.

Parameters
  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • buffers (list) – Log buffers to clear. Valid buffers are “radio”, “events”, and “main”. Defaults to “main”.

Raises

ADBTimeoutError ADBError

command(cmds, timeout=None)

Executes an adb command on the host against the device.

Parameters
  • cmds (list) – The command and its arguments to be executed.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

ADBProcess

command() provides a low level interface for executing commands for a specific device on the host via adb.

command() executes on the host in such a fashion that stdout of the adb process are file handles on the host and the exit code is available as the exit code of the adb process.

For executing shell commands on the device, use ADBDevice.shell(). The caller provides a list containing commands, as well as a timeout period in seconds.

A subprocess is spawned to execute adb for the device with stdout and stderr directed to a temporary file. If the process takes longer than the specified timeout, the process is terminated.

It is the caller’s responsibilty to clean up by closing the stdout temporary file.

command_output(cmds, timeout=None)

Executes an adb command on the host against the device returning stdout.

Parameters
  • cmds (list) – The command and its arguments to be executed.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

str - content of stdout.

Raises

ADBTimeoutError ADBError

cp(source, destination, recursive=False, timeout=None)

Copies a file or directory on the device.

Parameters
  • source – string containing the path of the source file or directory.

  • destination – string containing the path of the destination file or directory.

  • recursive – optional boolean indicating if a recursive copy is to be performed. Required if the source is a directory. Defaults to False. Think cp -R source destination.

  • timeout (int) – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

create_socket_connection(direction, local, remote, allow_rebind=True, timeout=None)

Sets up a socket connection in the specified direction.

Parameters
  • direction (str) – Direction of the socket connection

  • local (str) – Local port

  • remote (str) – Remote port

  • allow_rebind (bool) – Do not fail if port is already bound

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ValueError ADBTimeoutError ADBError

enable_run_as_for_path(path)
property enforcing
exists(path, timeout=None)

Returns True if the path exists on the device.

Parameters
  • path (str) – The path name on the device.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • root (bool) – Flag specifying if the command should be executed as root.

Returns

boolean - True if path exists.

Raises

ADBTimeoutError

forward(local, remote, allow_rebind=True, timeout=None)

Forward a local port to a specific port on the device.

See ADBDevice.create_socket_connection.

get_battery_percentage(timeout=None)

Returns the battery charge as a percentage.

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

battery charge as a percentage.

Raises

ADBTimeoutError ADBError

get_file(remote, offset=None, length=None, timeout=None)

Pull file from device and return the file’s content

Parameters
  • remote (str) – The path of the remote file.

  • offset – If specified, return only content beyond this offset.

  • length – If specified, limit content length accordingly.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

get_info(directive=None, timeout=None)

Returns a dictionary of information strings about the device.

Parameters
  • directive

    information you want to get. Options are:
    • battery - battery charge as a percentage

    • disk - total, free, available bytes on disk

    • id - unique id of the device

    • os - name of the os

    • process - list of running processes (same as ps)

    • systime - system time of the device

    • uptime - uptime of the device

    If directive is None, will return all available information

  • timeout (int) – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

get_ip_address(interfaces=None, timeout=None)

Returns the device’s ip address, or None if it doesn’t have one

Parameters
  • interfaces (list) – Interfaces to allow, or None to allow any non-loopback interface.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

str ip address of the device or None if it could not be found.

Raises

ADBTimeoutError ADBError

get_logcat(filter_specs=['dalvikvm:I', 'ConnectivityService:S', 'WifiMonitor:S', 'WifiStateTracker:S', 'wpa_supplicant:S', 'NetworkStateTracker:S', 'EmulatedCamera_Camera:S', 'EmulatedCamera_Device:S', 'EmulatedCamera_FakeCamera:S', 'EmulatedCamera_FakeDevice:S', 'EmulatedCamera_CallbackNotifier:S', 'GnssLocationProvider:S', 'Hyphenator:S', 'BatteryStats:S'], format='time', filter_out_regexps=[], timeout=None, buffers=[])

Returns the contents of the logcat file as a list of strings.

Parameters
  • filter_specs (list) – Optional logcat messages to be included.

  • format (str) – Optional logcat format.

  • filter_out_regexps (list) – Optional logcat messages to be excluded.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • buffers (list) – Log buffers to retrieve. Valid buffers are “radio”, “events”, and “main”. Defaults to “main”.

Returns

list of lines logcat output.

Raises

ADBTimeoutError ADBError

get_process_list(timeout=None)

Returns list of tuples (pid, name, user) for running processes on device.

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

list of (pid, name, user) tuples for running processes on the device.

Raises

ADBTimeoutError ADBError

get_prop(prop, timeout=None)

Gets value of a property from the device via adb shell getprop.

Parameters
  • prop (str) – The propery name.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

str value of property.

Raises

ADBTimeoutError ADBError

get_state(timeout=None)

Returns the device’s state via adb get-state.

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

str value of adb get-state.

Raises

ADBTimeoutError ADBError

get_sysinfo(timeout=None)

Returns a detailed dictionary of information strings about the device.

Parameters

timeout (int) – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError

get_top_activity(timeout=None)

Returns the name of the top activity (focused app) reported by dumpsys

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

package name of top activity or None (cannot be determined)

Raises

ADBTimeoutError ADBError

grant_runtime_permissions(app_name, timeout=None)

Grant required runtime permissions to the specified app (typically org.mozilla.fennec_$USER).

Parameters

str – app_name: Name of application (e.g. org.mozilla.fennec)

install_app(apk_path, replace=False, timeout=None)

Installs an app on the device.

Parameters
  • apk_path (str) – The apk file name to be installed.

  • replace (bool) – If True, replace existing application.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Returns

string - name of installed package.

Raises

ADBTimeoutError ADBError

is_app_installed(app_name, timeout=None)

Returns True if an app is installed on the device.

Parameters
  • app_name (str) – name of the app to be checked.

  • timeout (int) – maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

is_device_ready(timeout=None)

Checks if a device is ready for testing.

This method uses the android only package manager to check for readiness.

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

is_dir(path, timeout=None)

Returns True if path is an existing directory on the device.

Parameters
  • path (str) – The directory on the device.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

boolean - True if path exists on the device and is a directory.

Raises

ADBTimeoutError

is_file(path, timeout=None)

Returns True if path is an existing file on the device.

Parameters
  • path (str) – The file name on the device.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

boolean - True if path exists on the device and is a file.

Raises

ADBTimeoutError

is_path_internal_storage(path, timeout=None)

Return True if the path matches an internal storage path as defined by either ‘/sdcard’, ‘/mnt/sdcard’, or any of the .*_STORAGE environment variables on the device otherwise False.

Parameters
  • path (str) – The path to test.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

boolean

Raises

ADBTimeoutError ADBError

property is_rooted
kill(pids, sig=None, attempts=3, wait=5, timeout=None)

Kills processes on the device given a list of process ids.

Parameters
  • pids (list) – process ids to be killed.

  • sig (int) – signal to be sent to the process.

  • attempts (integer) – number of attempts to try to kill the processes.

  • wait (integer) – number of seconds to wait after each attempt.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

launch_activity(app_name, activity_name=None, intent='android.intent.action.MAIN', moz_env=None, extra_args=None, url=None, e10s=False, wait=True, fail_if_running=True, timeout=None)

Convenience method to launch an application on Android with various debugging arguments; convenient for geckoview apps.

Parameters
  • app_name (str) – Name of application (e.g. org.mozilla.geckoview_example or org.mozilla.geckoview.test)

  • activity_name (str) – Activity name, like GeckoViewActivity, or TestRunnerActivity.

  • intent (str) – Intent to launch application.

  • moz_env (str) – Mozilla specific environment to pass into application.

  • extra_args (str) – Extra arguments to be parsed by the app.

  • url (str) – URL to open

  • e10s (bool) – If True, run in multiprocess mode.

  • wait (bool) – If True, wait for application to start before returning.

  • fail_if_running (bool) – Raise an exception if instance of application is already running.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

launch_application(app_name, activity_name, intent, url=None, extras=None, wait=True, fail_if_running=True, grant_runtime_permissions=True, timeout=None)

Launches an Android application

Parameters
  • app_name (str) – Name of application (e.g. com.android.chrome)

  • activity_name (str) – Name of activity to launch (e.g. .Main)

  • intent (str) – Intent to launch application with

  • url (str) – URL to open

  • extras (dict) – Extra arguments for application.

  • wait (bool) – If True, wait for application to start before returning.

  • fail_if_running (bool) – Raise an exception if instance of application is already running.

  • grant_runtime_permissions (bool) – Grant special runtime permissions.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

launch_fennec(app_name, intent='android.intent.action.VIEW', moz_env=None, extra_args=None, url=None, wait=True, fail_if_running=True, timeout=None)

Convenience method to launch Fennec on Android with various debugging arguments

Parameters
  • app_name (str) – Name of fennec application (e.g. org.mozilla.fennec)

  • intent (str) – Intent to launch application.

  • moz_env (str) – Mozilla specific environment to pass into application.

  • extra_args (str) – Extra arguments to be parsed by fennec.

  • url (str) – URL to open

  • wait (bool) – If True, wait for application to start before returning.

  • fail_if_running (bool) – Raise an exception if instance of application is already running.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

list_files(path, timeout=None)

Return a list of files/directories contained in a directory on the device.

Parameters
  • path (str) – The directory name on the device.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

list of files/directories contained in the directory.

Raises

ADBTimeoutError

list_forwards(timeout=None)

Return a list of tuples specifying active forwards.

See ADBDevice.list_socket_connection.

list_reverses(timeout=None)

Returns a list of tuples showing active reverse socket connections.

See ADBDevice.list_socket_connection.

list_socket_connections(direction, timeout=None)

Return a list of tuples specifying active socket connectionss.

Return values are of the form (device, local, remote).

Parameters
  • direction (str) – ‘forward’ to list forward socket connections ‘reverse’ to list reverse socket connections

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ValueError ADBTimeoutError ADBError

ls(path, recursive=False, timeout=None)

Return a list of matching files/directories on the device.

The ls method emulates the behavior of the ls shell command. It differs from the list_files method by supporting wild cards and returning matches even if the path is not a directory and by allowing a recursive listing.

ls /sdcard always returns /sdcard and not the contents of the sdcard path. The ls method makes the behavior consistent with others paths by adjusting /sdcard to /sdcard/. Note this is also the case of other sdcard related paths such as /storage/emulated/legacy but no adjustment is made in those cases.

The ls method works around a Nexus 4 bug which prevents recursive listing of directories on the sdcard unless the path ends with “/” by adjusting sdcard paths ending in “/” to end with “/”. This adjustment is only made on official Nexus 4 builds with property ro.product.model “Nexus 4”. Note that this will fail to return any “hidden” files or directories which begin with “.”.

Parameters
  • path (str) – The directory name on the device.

  • recursive (bool) – Flag specifying if a recursive listing is to be returned. If recursive is False, the returned matches will be relative to the path. If recursive is True, the returned matches will be absolute paths.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

list of files/directories contained in the directory.

Raises

ADBTimeoutError

mkdir(path, parents=False, timeout=None)

Create a directory on the device.

Parameters
  • path (str) – The directory name on the device to be created.

  • parents (bool) – Flag indicating if the parent directories are also to be created. Think mkdir -p path.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

mv(source, destination, timeout=None)

Moves a file or directory on the device.

Parameters
  • source – string containing the path of the source file or directory.

  • destination – string containing the path of the destination file or directory.

  • timeout (int) – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

pkill(appname, sig=None, attempts=3, wait=5, timeout=None)

Kills a processes on the device matching a name.

Parameters
  • appname (str) – The app name of the process to be killed. Note that only the first 75 characters of the process name are significant.

  • sig (int) – optional signal to be sent to the process.

  • attempts (integer) – number of attempts to try to kill the processes.

  • wait (integer) – number of seconds to wait after each attempt.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • root (bool) – Flag specifying if the command should be executed as root.

Raises

ADBTimeoutError ADBError

power_on(timeout=None)

Sets the device’s power stayon value.

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

process_exist(process_name, timeout=None)

Returns True if process with name process_name is running on device.

Parameters
  • process_name (str) – The name of the process to check. Note that only the first 75 characters of the process name are significant.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

boolean - True if process exists.

Raises

ADBTimeoutError ADBError

pull(remote, local, timeout=None)

Pulls a file or directory from the device.

Parameters
  • remote (str) – The path of the remote file or directory.

  • local (str) – The path of the local file or directory name.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

push(local, remote, timeout=None)

Pushes a file or directory to the device.

Parameters
  • local (str) – The name of the local file or directory name.

  • remote (str) – The name of the remote file or directory name.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

reboot(timeout=None)

Reboots the device.

Parameters

timeout (int) – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

reboot() reboots the device, issues an adb wait-for-device in order to wait for the device to complete rebooting, then calls is_device_ready() to determine if the device has completed booting.

If the device supports running adbd as root, adbd will be restarted running as root. Then, if the device supports SELinux, setenforce Permissive will be called to change SELinux to permissive. This must be done after adbd is restarted in order for the SELinux Permissive setting to persist.

remount(timeout=None)

Remount /system/ in read/write mode

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

remove_forwards(local=None, timeout=None)

Remove existing port forwards.

See ADBDevice.remove_socket_connection.

remove_reverses(local=None, timeout=None)

Remove existing reverse socket connections.

See ADBDevice.remove_socket_connection.

remove_socket_connections(direction, local=None, timeout=None)

Remove existing socket connections for a given direction.

Parameters
  • direction (str) – ‘forward’ to remove forward socket connection ‘reverse’ to remove reverse socket connection

  • local (str) – local port specifier as for ADBDevice.forward. If local is not specified removes all forwards.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ValueError ADBTimeoutError ADBError

reverse(local, remote, allow_rebind=True, timeout=None)

Sets up a reverse socket connection from device to host.

See ADBDevice.create_socket_connection.

rm(path, recursive=False, force=False, timeout=None)

Delete files or directories on the device.

Parameters
  • path (str) – The path of the remote file or directory.

  • recursive (bool) – Flag specifying if the command is to be applied recursively to the target. Default is False.

  • force (bool) – Flag which if True will not raise an error when attempting to delete a non-existent file. Default is False.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

rmdir(path, timeout=None)

Delete empty directory on the device.

Parameters
  • path (str) – The directory name on the device.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

property run_as_package

Returns the name of the package which will be used in run-as to change the effective user executing a command.

property selinux

Returns True if SELinux is supported, False otherwise.

shell(cmd, env=None, cwd=None, timeout=None, stdout_callback=None, enable_run_as=False)

Executes a shell command on the device.

Parameters
  • cmd (str) – The command to be executed.

  • env (dict) – Contains the environment variables and their values.

  • cwd (str) – The directory from which to execute.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • stdout_callback (function) – Function called for each line of output.

  • enable_run_as (bool) – Flag used to temporarily enable use of run-as to execute the command.

Returns

ADBProcess

shell() provides a low level interface for executing commands on the device via adb shell.

shell() executes on the host in such as fashion that stdout contains the stdout and stderr of the host abd process combined with the stdout and stderr of the shell command on the device. The exit code of shell() is the exit code of the adb command if it was non-zero or the extracted exit code from the output of the shell command executed on the device.

The caller provides a flag indicating if the command is to be executed as root, a string for any requested working directory, a hash defining the environment, a string containing shell commands, as well as a timeout period in seconds.

The command line to be executed is created to set the current directory, set the required environment variables, optionally execute the command using su and to output the return code of the command to stdout. The command list is created as a command sequence separated by && which will terminate the command sequence on the first command which returns a non-zero exit code.

A subprocess is spawned to execute adb shell for the device with stdout and stderr directed to a temporary file. If the process takes longer than the specified timeout, the process is terminated. The return code is extracted from the stdout and is then removed from the file.

It is the caller’s responsibilty to clean up by closing the stdout temporary files.

shell_bool(cmd, env=None, cwd=None, timeout=None, enable_run_as=False)

Executes a shell command on the device returning True on success and False on failure.

Parameters
  • cmd (str) – The command to be executed.

  • env (dict) – Contains the environment variables and their values.

  • cwd (str) – The directory from which to execute.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • enable_run_as (bool) – Flag used to temporarily enable use of run-as to execute the command.

Returns

bool

Raises

ADBTimeoutError

shell_output(cmd, env=None, cwd=None, timeout=None, enable_run_as=False)

Executes an adb shell on the device returning stdout.

Parameters
  • cmd (str) – The command to be executed.

  • env (dict) – Contains the environment variables and their values.

  • cwd (str) – The directory from which to execute.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • enable_run_as (bool) – Flag used to temporarily enable use of run-as to execute the command.

Returns

str - content of stdout.

Raises

ADBTimeoutError ADBError

stop_application(app_name, timeout=None)

Stops the specified application

For Android 3.0+, we use the “am force-stop” to do this, which is reliable and does not require root. For earlier versions of Android, we simply try to manually kill the processes started by the app repeatedly until none is around any more. This is less reliable and does require root.

Parameters
  • app_name (str) – Name of application (e.g. com.android.chrome)

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

  • root (bool) – Flag specifying if the command should be executed as root.

Raises

ADBTimeoutError ADBError

property test_root

The test_root property returns the directory on the device where temporary test files are stored.

The first time test_root it is called it determines and caches a value for the test root on the device. It determines the appropriate test root by attempting to create a ‘proof’ directory on each of a list of directories and returning the first successful directory as the test_root value. The cached value for the test_root will be shared by subsequent instances of ADBDevice if self._share_test_root is True.

The default list of directories checked by test_root are:

  • /data/local/tmp/test_root

You may override the default list by providing a test_root argument to the ADBDevice constructor which will then be used when attempting to create the ‘proof’ directory.

Raises

ADBTimeoutError ADBError

uninstall_app(app_name, reboot=False, timeout=None)

Uninstalls an app on the device.

Parameters
  • app_name (str) – The name of the app to be uninstalled.

  • reboot (bool) – Flag indicating that the device should be rebooted after the app is uninstalled. No reboot occurs if the app is not installed.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

update_app(apk_path, timeout=None)

Updates an app on the device and reboots.

Parameters
  • apk_path (str) – The apk file name to be updated.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

class mozdevice.ADBCommand(adb='adb', adb_host=None, adb_port=None, logger_name='adb', timeout=300, verbose=False, use_root=True)

Bases: object

ADBCommand provides a basic interface to adb commands which is used to provide the ‘command’ methods for the classes ADBHost and ADBDevice.

ADBCommand should only be used as the base class for other classes and should not be instantiated directly. To enforce this restriction calling ADBCommand’s constructor will raise a NonImplementedError exception.

Parameters
  • adb (str) – path to adb executable. Defaults to ‘adb’.

  • adb_host (str) – host of the adb server.

  • adb_port (int) – port of the adb server.

  • logger_name (str) – logging logger name. Defaults to ‘adb’.

  • timeout (int) – The default maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value defaults to 300.

  • verbose (bool) – provide verbose output

  • use_root (bool) – Use root if available on device

Raises

ADBError ADBTimeoutError

from mozdevice import ADBCommand

try:
    adbcommand = ADBCommand()
except NotImplementedError:
    print "ADBCommand can not be instantiated."
command(cmds, device_serial=None, timeout=None)

Executes an adb command on the host.

Parameters
  • cmds (list) – The command and its arguments to be executed.

  • device_serial (str) – The device’s serial number if the adb command is to be executed against a specific device. If it is not specified, ANDROID_SERIAL from the environment will be used if it is set.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBCommand constructor is used.

Returns

ADBProcess

command() provides a low level interface for executing commands on the host via adb.

command() executes on the host in such a fashion that stdout of the adb process is a file handle on the host and the exit code is available as the exit code of the adb process.

The caller provides a list containing commands, as well as a timeout period in seconds.

A subprocess is spawned to execute adb with stdout and stderr directed to a temporary file. If the process takes longer than the specified timeout, the process is terminated.

It is the caller’s responsibilty to clean up by closing the stdout temporary file.

command_output(cmds, device_serial=None, timeout=None)

Executes an adb command on the host returning stdout.

Parameters
  • cmds (list) – The command and its arguments to be executed.

  • device_serial (str) – The device’s serial number if the adb command is to be executed against a specific device. If it is not specified, ANDROID_SERIAL from the environment will be used if it is set.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBCommand constructor is used.

Returns

str - content of stdout.

Raises

ADBTimeoutError ADBError

class mozdevice.ADBDevice(device=None, adb='adb', adb_host=None, adb_port=None, test_root=None, logger_name='adb', timeout=300, verbose=False, device_ready_retry_wait=20, device_ready_retry_attempts=3, use_root=True, share_test_root=True, run_as_package=None)

Bases: mozdevice.adb.ADBCommand

ADBDevice provides methods which can be used to interact with the associated Android-based device.

Parameters
  • device (str) – When a string is passed in device, it is interpreted as the device serial number. This form is not compatible with devices containing a “:” in the serial; in this case ValueError will be raised. When a dictionary is passed it must have one or both of the keys “device_serial” and “usb”. This is compatible with the dictionaries in the list returned by ADBHost.devices(). If the value of device_serial is a valid serial not containing a “:” it will be used to identify the device, otherwise the value of the usb key, prefixed with “usb:” is used. If None is passed and there is exactly one device attached to the host, that device is used. If None is passed and ANDROID_SERIAL is set in the environment, that device is used. If there is more than one device attached and device is None and ANDROID_SERIAL is not set in the environment, ValueError is raised. If no device is attached the constructor will block until a device is attached or the timeout is reached.

  • adb_host (str) – host of the adb server to connect to.

  • adb_port (int) – port of the adb server to connect to.

  • test_root (str) – value containing the test root to be used on the device. This value will be shared among all instances of ADBDevice if share_test_root is True.

  • logger_name (str) – logging logger name. Defaults to ‘adb’

  • timeout (int) – The default maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value defaults to 300.

  • verbose (bool) – provide verbose output

  • device_ready_retry_wait (int) – number of seconds to wait between attempts to check if the device is ready after a reboot.

  • device_ready_retry_attempts (integer) – number of attempts when checking if a device is ready.

  • use_root (bool) – Use root if it is available on device

  • share_test_root (bool) – True if instance should share the same test_root value with other ADBInstances. Defaults to True.

  • run_as_package (str) – Name of package to be used in run-as in liew of using su.

Raises

ADBError ADBTimeoutError ValueError

from mozdevice import ADBDevice

adbdevice = ADBDevice()
print(adbdevice.list_files("/mnt/sdcard"))
if adbdevice.process_exist("org.mozilla.geckoview.test"):
    print("org.mozilla.geckoview.test is running")
SOCKET_DIRECTION_FORWARD = 'forward'
SOCKET_DIRECTION_REVERSE = 'reverse'
batch_execute(commands, timeout=None, enable_run_as=False)

Writes commands to a temporary file then executes on the device.

Parameters
  • commands_list (list) – List of commands to be run by the shell.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • enable_run_as (bool) – Flag used to temporarily enable use of run-as to execute the command.

Raises

ADBTimeoutError ADBError

chmod(path, recursive=False, mask='777', timeout=None)

Recursively changes the permissions of a directory on the device.

Parameters
  • path (str) – The directory name on the device.

  • recursive (bool) – Flag specifying if the command should be executed recursively.

  • mask (str) – The octal permissions.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

chown(path, owner, group=None, recursive=False, timeout=None)

Run the chown command on the provided path.

Parameters
  • path (str) – path name on the device.

  • owner (str) – new owner of the path.

  • group (str) – optional parameter specifying the new group the path should belong to.

  • recursive (bool) – optional value specifying whether the command should operate on files and directories recursively.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

clear_logcat(timeout=None, buffers=[])

Clears logcat via adb logcat -c.

Parameters
  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • buffers (list) – Log buffers to clear. Valid buffers are “radio”, “events”, and “main”. Defaults to “main”.

Raises

ADBTimeoutError ADBError

command(cmds, timeout=None)

Executes an adb command on the host against the device.

Parameters
  • cmds (list) – The command and its arguments to be executed.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

ADBProcess

command() provides a low level interface for executing commands for a specific device on the host via adb.

command() executes on the host in such a fashion that stdout of the adb process are file handles on the host and the exit code is available as the exit code of the adb process.

For executing shell commands on the device, use ADBDevice.shell(). The caller provides a list containing commands, as well as a timeout period in seconds.

A subprocess is spawned to execute adb for the device with stdout and stderr directed to a temporary file. If the process takes longer than the specified timeout, the process is terminated.

It is the caller’s responsibilty to clean up by closing the stdout temporary file.

command_output(cmds, timeout=None)

Executes an adb command on the host against the device returning stdout.

Parameters
  • cmds (list) – The command and its arguments to be executed.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

str - content of stdout.

Raises

ADBTimeoutError ADBError

cp(source, destination, recursive=False, timeout=None)

Copies a file or directory on the device.

Parameters
  • source – string containing the path of the source file or directory.

  • destination – string containing the path of the destination file or directory.

  • recursive – optional boolean indicating if a recursive copy is to be performed. Required if the source is a directory. Defaults to False. Think cp -R source destination.

  • timeout (int) – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

create_socket_connection(direction, local, remote, allow_rebind=True, timeout=None)

Sets up a socket connection in the specified direction.

Parameters
  • direction (str) – Direction of the socket connection

  • local (str) – Local port

  • remote (str) – Remote port

  • allow_rebind (bool) – Do not fail if port is already bound

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ValueError ADBTimeoutError ADBError

enable_run_as_for_path(path)
property enforcing
exists(path, timeout=None)

Returns True if the path exists on the device.

Parameters
  • path (str) – The path name on the device.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • root (bool) – Flag specifying if the command should be executed as root.

Returns

boolean - True if path exists.

Raises

ADBTimeoutError

forward(local, remote, allow_rebind=True, timeout=None)

Forward a local port to a specific port on the device.

See ADBDevice.create_socket_connection.

get_battery_percentage(timeout=None)

Returns the battery charge as a percentage.

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

battery charge as a percentage.

Raises

ADBTimeoutError ADBError

get_file(remote, offset=None, length=None, timeout=None)

Pull file from device and return the file’s content

Parameters
  • remote (str) – The path of the remote file.

  • offset – If specified, return only content beyond this offset.

  • length – If specified, limit content length accordingly.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

get_info(directive=None, timeout=None)

Returns a dictionary of information strings about the device.

Parameters
  • directive

    information you want to get. Options are:
    • battery - battery charge as a percentage

    • disk - total, free, available bytes on disk

    • id - unique id of the device

    • os - name of the os

    • process - list of running processes (same as ps)

    • systime - system time of the device

    • uptime - uptime of the device

    If directive is None, will return all available information

  • timeout (int) – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

get_ip_address(interfaces=None, timeout=None)

Returns the device’s ip address, or None if it doesn’t have one

Parameters
  • interfaces (list) – Interfaces to allow, or None to allow any non-loopback interface.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

str ip address of the device or None if it could not be found.

Raises

ADBTimeoutError ADBError

get_logcat(filter_specs=['dalvikvm:I', 'ConnectivityService:S', 'WifiMonitor:S', 'WifiStateTracker:S', 'wpa_supplicant:S', 'NetworkStateTracker:S', 'EmulatedCamera_Camera:S', 'EmulatedCamera_Device:S', 'EmulatedCamera_FakeCamera:S', 'EmulatedCamera_FakeDevice:S', 'EmulatedCamera_CallbackNotifier:S', 'GnssLocationProvider:S', 'Hyphenator:S', 'BatteryStats:S'], format='time', filter_out_regexps=[], timeout=None, buffers=[])

Returns the contents of the logcat file as a list of strings.

Parameters
  • filter_specs (list) – Optional logcat messages to be included.

  • format (str) – Optional logcat format.

  • filter_out_regexps (list) – Optional logcat messages to be excluded.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • buffers (list) – Log buffers to retrieve. Valid buffers are “radio”, “events”, and “main”. Defaults to “main”.

Returns

list of lines logcat output.

Raises

ADBTimeoutError ADBError

get_process_list(timeout=None)

Returns list of tuples (pid, name, user) for running processes on device.

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

list of (pid, name, user) tuples for running processes on the device.

Raises

ADBTimeoutError ADBError

get_prop(prop, timeout=None)

Gets value of a property from the device via adb shell getprop.

Parameters
  • prop (str) – The propery name.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

str value of property.

Raises

ADBTimeoutError ADBError

get_state(timeout=None)

Returns the device’s state via adb get-state.

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

str value of adb get-state.

Raises

ADBTimeoutError ADBError

get_sysinfo(timeout=None)

Returns a detailed dictionary of information strings about the device.

Parameters

timeout (int) – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError

get_top_activity(timeout=None)

Returns the name of the top activity (focused app) reported by dumpsys

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

package name of top activity or None (cannot be determined)

Raises

ADBTimeoutError ADBError

grant_runtime_permissions(app_name, timeout=None)

Grant required runtime permissions to the specified app (typically org.mozilla.fennec_$USER).

Parameters

str – app_name: Name of application (e.g. org.mozilla.fennec)

install_app(apk_path, replace=False, timeout=None)

Installs an app on the device.

Parameters
  • apk_path (str) – The apk file name to be installed.

  • replace (bool) – If True, replace existing application.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Returns

string - name of installed package.

Raises

ADBTimeoutError ADBError

is_app_installed(app_name, timeout=None)

Returns True if an app is installed on the device.

Parameters
  • app_name (str) – name of the app to be checked.

  • timeout (int) – maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

is_device_ready(timeout=None)

Checks if a device is ready for testing.

This method uses the android only package manager to check for readiness.

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

is_dir(path, timeout=None)

Returns True if path is an existing directory on the device.

Parameters
  • path (str) – The directory on the device.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

boolean - True if path exists on the device and is a directory.

Raises

ADBTimeoutError

is_file(path, timeout=None)

Returns True if path is an existing file on the device.

Parameters
  • path (str) – The file name on the device.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

boolean - True if path exists on the device and is a file.

Raises

ADBTimeoutError

is_path_internal_storage(path, timeout=None)

Return True if the path matches an internal storage path as defined by either ‘/sdcard’, ‘/mnt/sdcard’, or any of the .*_STORAGE environment variables on the device otherwise False.

Parameters
  • path (str) – The path to test.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

boolean

Raises

ADBTimeoutError ADBError

property is_rooted
kill(pids, sig=None, attempts=3, wait=5, timeout=None)

Kills processes on the device given a list of process ids.

Parameters
  • pids (list) – process ids to be killed.

  • sig (int) – signal to be sent to the process.

  • attempts (integer) – number of attempts to try to kill the processes.

  • wait (integer) – number of seconds to wait after each attempt.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

launch_activity(app_name, activity_name=None, intent='android.intent.action.MAIN', moz_env=None, extra_args=None, url=None, e10s=False, wait=True, fail_if_running=True, timeout=None)

Convenience method to launch an application on Android with various debugging arguments; convenient for geckoview apps.

Parameters
  • app_name (str) – Name of application (e.g. org.mozilla.geckoview_example or org.mozilla.geckoview.test)

  • activity_name (str) – Activity name, like GeckoViewActivity, or TestRunnerActivity.

  • intent (str) – Intent to launch application.

  • moz_env (str) – Mozilla specific environment to pass into application.

  • extra_args (str) – Extra arguments to be parsed by the app.

  • url (str) – URL to open

  • e10s (bool) – If True, run in multiprocess mode.

  • wait (bool) – If True, wait for application to start before returning.

  • fail_if_running (bool) – Raise an exception if instance of application is already running.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

launch_application(app_name, activity_name, intent, url=None, extras=None, wait=True, fail_if_running=True, grant_runtime_permissions=True, timeout=None)

Launches an Android application

Parameters
  • app_name (str) – Name of application (e.g. com.android.chrome)

  • activity_name (str) – Name of activity to launch (e.g. .Main)

  • intent (str) – Intent to launch application with

  • url (str) – URL to open

  • extras (dict) – Extra arguments for application.

  • wait (bool) – If True, wait for application to start before returning.

  • fail_if_running (bool) – Raise an exception if instance of application is already running.

  • grant_runtime_permissions (bool) – Grant special runtime permissions.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

launch_fennec(app_name, intent='android.intent.action.VIEW', moz_env=None, extra_args=None, url=None, wait=True, fail_if_running=True, timeout=None)

Convenience method to launch Fennec on Android with various debugging arguments

Parameters
  • app_name (str) – Name of fennec application (e.g. org.mozilla.fennec)

  • intent (str) – Intent to launch application.

  • moz_env (str) – Mozilla specific environment to pass into application.

  • extra_args (str) – Extra arguments to be parsed by fennec.

  • url (str) – URL to open

  • wait (bool) – If True, wait for application to start before returning.

  • fail_if_running (bool) – Raise an exception if instance of application is already running.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

list_files(path, timeout=None)

Return a list of files/directories contained in a directory on the device.

Parameters
  • path (str) – The directory name on the device.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

list of files/directories contained in the directory.

Raises

ADBTimeoutError

list_forwards(timeout=None)

Return a list of tuples specifying active forwards.

See ADBDevice.list_socket_connection.

list_reverses(timeout=None)

Returns a list of tuples showing active reverse socket connections.

See ADBDevice.list_socket_connection.

list_socket_connections(direction, timeout=None)

Return a list of tuples specifying active socket connectionss.

Return values are of the form (device, local, remote).

Parameters
  • direction (str) – ‘forward’ to list forward socket connections ‘reverse’ to list reverse socket connections

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ValueError ADBTimeoutError ADBError

ls(path, recursive=False, timeout=None)

Return a list of matching files/directories on the device.

The ls method emulates the behavior of the ls shell command. It differs from the list_files method by supporting wild cards and returning matches even if the path is not a directory and by allowing a recursive listing.

ls /sdcard always returns /sdcard and not the contents of the sdcard path. The ls method makes the behavior consistent with others paths by adjusting /sdcard to /sdcard/. Note this is also the case of other sdcard related paths such as /storage/emulated/legacy but no adjustment is made in those cases.

The ls method works around a Nexus 4 bug which prevents recursive listing of directories on the sdcard unless the path ends with “/” by adjusting sdcard paths ending in “/” to end with “/”. This adjustment is only made on official Nexus 4 builds with property ro.product.model “Nexus 4”. Note that this will fail to return any “hidden” files or directories which begin with “.”.

Parameters
  • path (str) – The directory name on the device.

  • recursive (bool) – Flag specifying if a recursive listing is to be returned. If recursive is False, the returned matches will be relative to the path. If recursive is True, the returned matches will be absolute paths.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

list of files/directories contained in the directory.

Raises

ADBTimeoutError

mkdir(path, parents=False, timeout=None)

Create a directory on the device.

Parameters
  • path (str) – The directory name on the device to be created.

  • parents (bool) – Flag indicating if the parent directories are also to be created. Think mkdir -p path.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

mv(source, destination, timeout=None)

Moves a file or directory on the device.

Parameters
  • source – string containing the path of the source file or directory.

  • destination – string containing the path of the destination file or directory.

  • timeout (int) – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

pkill(appname, sig=None, attempts=3, wait=5, timeout=None)

Kills a processes on the device matching a name.

Parameters
  • appname (str) – The app name of the process to be killed. Note that only the first 75 characters of the process name are significant.

  • sig (int) – optional signal to be sent to the process.

  • attempts (integer) – number of attempts to try to kill the processes.

  • wait (integer) – number of seconds to wait after each attempt.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • root (bool) – Flag specifying if the command should be executed as root.

Raises

ADBTimeoutError ADBError

power_on(timeout=None)

Sets the device’s power stayon value.

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

process_exist(process_name, timeout=None)

Returns True if process with name process_name is running on device.

Parameters
  • process_name (str) – The name of the process to check. Note that only the first 75 characters of the process name are significant.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Returns

boolean - True if process exists.

Raises

ADBTimeoutError ADBError

pull(remote, local, timeout=None)

Pulls a file or directory from the device.

Parameters
  • remote (str) – The path of the remote file or directory.

  • local (str) – The path of the local file or directory name.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

push(local, remote, timeout=None)

Pushes a file or directory to the device.

Parameters
  • local (str) – The name of the local file or directory name.

  • remote (str) – The name of the remote file or directory name.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

reboot(timeout=None)

Reboots the device.

Parameters

timeout (int) – optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

reboot() reboots the device, issues an adb wait-for-device in order to wait for the device to complete rebooting, then calls is_device_ready() to determine if the device has completed booting.

If the device supports running adbd as root, adbd will be restarted running as root. Then, if the device supports SELinux, setenforce Permissive will be called to change SELinux to permissive. This must be done after adbd is restarted in order for the SELinux Permissive setting to persist.

remount(timeout=None)

Remount /system/ in read/write mode

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

remove_forwards(local=None, timeout=None)

Remove existing port forwards.

See ADBDevice.remove_socket_connection.

remove_reverses(local=None, timeout=None)

Remove existing reverse socket connections.

See ADBDevice.remove_socket_connection.

remove_socket_connections(direction, local=None, timeout=None)

Remove existing socket connections for a given direction.

Parameters
  • direction (str) – ‘forward’ to remove forward socket connection ‘reverse’ to remove reverse socket connection

  • local (str) – local port specifier as for ADBDevice.forward. If local is not specified removes all forwards.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ValueError ADBTimeoutError ADBError

reverse(local, remote, allow_rebind=True, timeout=None)

Sets up a reverse socket connection from device to host.

See ADBDevice.create_socket_connection.

rm(path, recursive=False, force=False, timeout=None)

Delete files or directories on the device.

Parameters
  • path (str) – The path of the remote file or directory.

  • recursive (bool) – Flag specifying if the command is to be applied recursively to the target. Default is False.

  • force (bool) – Flag which if True will not raise an error when attempting to delete a non-existent file. Default is False.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

rmdir(path, timeout=None)

Delete empty directory on the device.

Parameters
  • path (str) – The directory name on the device.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

Raises

ADBTimeoutError ADBError

property run_as_package

Returns the name of the package which will be used in run-as to change the effective user executing a command.

property selinux

Returns True if SELinux is supported, False otherwise.

shell(cmd, env=None, cwd=None, timeout=None, stdout_callback=None, enable_run_as=False)

Executes a shell command on the device.

Parameters
  • cmd (str) – The command to be executed.

  • env (dict) – Contains the environment variables and their values.

  • cwd (str) – The directory from which to execute.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • stdout_callback (function) – Function called for each line of output.

  • enable_run_as (bool) – Flag used to temporarily enable use of run-as to execute the command.

Returns

ADBProcess

shell() provides a low level interface for executing commands on the device via adb shell.

shell() executes on the host in such as fashion that stdout contains the stdout and stderr of the host abd process combined with the stdout and stderr of the shell command on the device. The exit code of shell() is the exit code of the adb command if it was non-zero or the extracted exit code from the output of the shell command executed on the device.

The caller provides a flag indicating if the command is to be executed as root, a string for any requested working directory, a hash defining the environment, a string containing shell commands, as well as a timeout period in seconds.

The command line to be executed is created to set the current directory, set the required environment variables, optionally execute the command using su and to output the return code of the command to stdout. The command list is created as a command sequence separated by && which will terminate the command sequence on the first command which returns a non-zero exit code.

A subprocess is spawned to execute adb shell for the device with stdout and stderr directed to a temporary file. If the process takes longer than the specified timeout, the process is terminated. The return code is extracted from the stdout and is then removed from the file.

It is the caller’s responsibilty to clean up by closing the stdout temporary files.

shell_bool(cmd, env=None, cwd=None, timeout=None, enable_run_as=False)

Executes a shell command on the device returning True on success and False on failure.

Parameters
  • cmd (str) – The command to be executed.

  • env (dict) – Contains the environment variables and their values.

  • cwd (str) – The directory from which to execute.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • enable_run_as (bool) – Flag used to temporarily enable use of run-as to execute the command.

Returns

bool

Raises

ADBTimeoutError

shell_output(cmd, env=None, cwd=None, timeout=None, enable_run_as=False)

Executes an adb shell on the device returning stdout.

Parameters
  • cmd (str) – The command to be executed.

  • env (dict) – Contains the environment variables and their values.

  • cwd (str) – The directory from which to execute.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBDevice constructor is used.

  • enable_run_as (bool) – Flag used to temporarily enable use of run-as to execute the command.

Returns

str - content of stdout.

Raises

ADBTimeoutError ADBError

stop_application(app_name, timeout=None)

Stops the specified application

For Android 3.0+, we use the “am force-stop” to do this, which is reliable and does not require root. For earlier versions of Android, we simply try to manually kill the processes started by the app repeatedly until none is around any more. This is less reliable and does require root.

Parameters
  • app_name (str) – Name of application (e.g. com.android.chrome)

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

  • root (bool) – Flag specifying if the command should be executed as root.

Raises

ADBTimeoutError ADBError

property test_root

The test_root property returns the directory on the device where temporary test files are stored.

The first time test_root it is called it determines and caches a value for the test root on the device. It determines the appropriate test root by attempting to create a ‘proof’ directory on each of a list of directories and returning the first successful directory as the test_root value. The cached value for the test_root will be shared by subsequent instances of ADBDevice if self._share_test_root is True.

The default list of directories checked by test_root are:

  • /data/local/tmp/test_root

You may override the default list by providing a test_root argument to the ADBDevice constructor which will then be used when attempting to create the ‘proof’ directory.

Raises

ADBTimeoutError ADBError

uninstall_app(app_name, reboot=False, timeout=None)

Uninstalls an app on the device.

Parameters
  • app_name (str) – The name of the app to be uninstalled.

  • reboot (bool) – Flag indicating that the device should be rebooted after the app is uninstalled. No reboot occurs if the app is not installed.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

update_app(apk_path, timeout=None)

Updates an app on the device and reboots.

Parameters
  • apk_path (str) – The apk file name to be updated.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used.

Raises

ADBTimeoutError ADBError

mozdevice.ADBDeviceFactory(device=None, adb='adb', adb_host=None, adb_port=None, test_root=None, logger_name='adb', timeout=300, verbose=False, device_ready_retry_wait=20, device_ready_retry_attempts=3, use_root=True, share_test_root=True, run_as_package=None)

ADBDeviceFactory provides a factory for ADBDevice instances that enforces the requirement that only one ADBDevice be created for each attached device. It uses the identical arguments as the ADBDevice constructor. This is also used to ensure that the device’s test_root is initialized to an empty directory before tests are run on the device.

Returns

ADBDevice

Raises

ADBDeviceFactoryError ADBError ADBTimeoutError

exception mozdevice.ADBError

Bases: Exception

ADBError is raised in situations where a command executed on a device either exited with a non-zero exitcode or when an unexpected error condition has occurred. Generally, ADBErrors can be handled and the device can continue to be used.

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class mozdevice.ADBHost(adb='adb', adb_host=None, adb_port=None, logger_name='adb', timeout=300, verbose=False)

Bases: mozdevice.adb.ADBCommand

ADBHost provides a basic interface to adb host commands which do not target a specific device.

Parameters
  • adb (str) – path to adb executable. Defaults to ‘adb’.

  • adb_host (str) – host of the adb server.

  • adb_port (int) – port of the adb server.

  • logger_name – logging logger name. Defaults to ‘adb’.

  • timeout (int) – The default maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value defaults to 300.

  • verbose (bool) – provide verbose output

Raises

ADBError ADBTimeoutError

from mozdevice import ADBHost

adbhost = ADBHost()
adbhost.start_server()
command(cmds, timeout=None)

Executes an adb command on the host.

Parameters
  • cmds (list) – The command and its arguments to be executed.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBHost constructor is used.

Returns

ADBProcess

command() provides a low level interface for executing commands on the host via adb.

command() executes on the host in such a fashion that stdout of the adb process is a file handle on the host and the exit code is available as the exit code of the adb process.

The caller provides a list containing commands, as well as a timeout period in seconds.

A subprocess is spawned to execute adb with stdout and stderr directed to a temporary file. If the process takes longer than the specified timeout, the process is terminated.

It is the caller’s responsibilty to clean up by closing the stdout temporary file.

command_output(cmds, timeout=None)

Executes an adb command on the host returning stdout.

Parameters
  • cmds (list) – The command and its arguments to be executed.

  • timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBHost constructor is used.

Returns

str - content of stdout.

Raises

ADBTimeoutError ADBError

devices(timeout=None)

Executes adb devices -l and returns a list of objects describing attached devices.

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBHost constructor is used.

Returns

an object contain

Raises

ADBTimeoutError ADBListDevicesError ADBError

The output of adb devices -l

$ adb devices -l
List of devices attached
b313b945               device usb:1-7 product:d2vzw model:SCH_I535 device:d2vzw

is parsed and placed into an object as in

[{'device_serial': 'b313b945', 'state': 'device', 'product': 'd2vzw',
  'usb': '1-7', 'device': 'd2vzw', 'model': 'SCH_I535' }]
kill_server(timeout=None)

Kills the adb server.

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBHost constructor is used.

Raises

ADBTimeoutError ADBError

start_server(timeout=None)

Starts the adb server.

Parameters

timeout (int) – The maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADBHost constructor is used.

Raises

ADBTimeoutError ADBError

Attempting to use start_server with any adb_host value other than None will fail with an ADBError exception.

You will need to start the server on the remote host via the command:

adb -a fork-server server

If you wish the remote adb server to restart automatically, you can enclose the command in a loop as in:

while true; do
  adb -a fork-server server
done
class mozdevice.ADBProcess(args)

Bases: object

ADBProcess encapsulates the data related to executing the adb process.

args

command argument list.

exitcode

exitcode of the process.

proc

subprocess Process object used to execute the command.

property stdout

Return the contents of stdout.

stdout_file

Temporary file handle to be used for stdout.

timedout

boolean indicating if the command timed out.

exception mozdevice.ADBProcessError(adb_process)

Bases: mozdevice.adb.ADBError

ADBProcessError is raised when an associated ADBProcess is available and relevant.

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception mozdevice.ADBTimeoutError

Bases: Exception

ADBTimeoutError is raised when either a host command or shell command takes longer than the specified timeout to execute. The timeout value is set in the ADBCommand constructor and is 300 seconds by default. This error is typically fatal since the host is having problems communicating with the device. You may be able to recover by rebooting, but this is not guaranteed.

Recovery options are:

  • Killing and restarting the adb server via

    adb kill-server; adb start-server
    
  • Rebooting the device manually.

  • Rebooting the host.

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.