Coder Social home page Coder Social logo

adbutils's Introduction

adbutils

PyPI codecov

Python adb library for adb service (Only support Python3.6+), Recommend 3.8+

Table of Contents

Install

pip3 install adbutils

Usage

Example

Connect ADB Server

import adbutils

adb = adbutils.AdbClient(host="127.0.0.1", port=5037)
for info in adb.list():
    print(info.serial, info.state)
    # <serial> <device|offline>

# only list state=device
print(adb.device_list())

# Set socket timeout to 10 (default None)
adb = adbutils.AdbClient(host="127.0.0.1", port=5037, socket_timeout=10)
print(adb.device_list())

The above code can be short to from adbutils import adb

List all the devices and get device object

from adbutils import adb

for d in adb.device_list():
    print(d.serial) # print device serial

d = adb.device(serial="33ff22xx")

# or
d = adb.device(transport_id=24) # transport_id can be found in: adb devices -l

# You do not need to offer serial if only one device connected
# RuntimeError will be raised if multi device connected
d = adb.device()

The following code will not write from adbutils import adb for short

Connect or disconnect remote device

Same as command adb connect

output = adb.connect("127.0.0.1:5555")
print(output)
# output: already connected to 127.0.0.1:5555

# connect with timeout
try:
    adb.connect("127.0.0.1:5555", timeout=3.0)
except AdbTimeout as e:
    print(e)

adb.disconnect("127.0.0.1:5555")
adb.disconnect("127.0.0.1:5555", raise_error=True) # if device is not present, AdbError will raise

# wait-for-device
adb.wait_for("127.0.0.1:5555", state="device") # wait for device online, state default value is "device"
adb.wait_for("127.0.0.1:5555", state="disconnect") # wait device disconnect

adb forward and adb reverse

Same as adb forward --list and adb reverse --list

# list all forwards
for item in adb.forward_list():
    print(item.serial, item.local, item.remote)
    # 8d1f93be tcp:10603 tcp:7912
    # 12345678 tcp:10664 tcp:7912

# list only one device forwards
for item in adb.forward_list("8d1f93be"):
    print(item.serial, item.local, item.remote)
    # 8d1f93be tcp:10603 tcp:7912
    # 12345678 tcp:10664 tcp:7912


for item in adb.reverse_list():
    print(item.serial, item.local, item.remote)

# 监控设备连接 track-devices
for event in adb.track_devices():
    print(event.present, event.serial, event.status)

## When plugin two device, output
# True WWUDU16C22003963 device
# True bf755cab device
# False bf755cab absent

# When adb-server killed, AdbError will be raised

Create socket connection to the device

For example

# minitouch: https://github.com/openstf/minitouch
c = d.create_connection("unix", "minitouch")
print(c.recv(500))
c.close()
c = d.create_connection("tcp", 7912) # the second argument must be int
c.send(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")
print(c.recv(500))
c.close()
# read device file
with d.create_connection(adbutils.Network.DEV, "/data/local/tmp/hello.txt") as c:
    print(c.recv(500))

There are many other usage, see SERVICES.TXT for more details

Thanks for Pull Request from @hfutxqd

Run shell command

I assume there is only one device connected.

import io
from adbutils import adb

d = adb.device()

print(d.serial) # 获取序列号

# Argument support list, str
serial = d.shell(["getprop", "ro.serial"]) # 获取Prop信息

# Same as
serial = d.shell("getprop ro.serial")

# Set timeout for shell command
d.shell("sleep 1", timeout=0.5) # Should raise adbutils.AdbTimeout

# The advanced shell (returncode archieved by add command suffix: ;echo EXIT:$?)
ret = d.shell2("echo 1")
print(ret)
# expect: ShellReturn(args='echo 1', returncode=0, output='1\n')

# show property, also based on d.shell
print(d.prop.name) # output example: surabaya
d.prop.model
d.prop.device
d.prop.get("ro.product.model")
d.prop.get("ro.product.model", cache=True) # a little faster, use cache data first

d.get_serialno() # same as adb get-serialno
d.get_devpath() # same as adb get-devpath
d.get_state() # same as adb get-state

Take screenshot

# Method 1 (Recommend)
pil_image = d.screenshot()

# Method 2
# adb exec-out screencap -p p.png
png_data = d.shell("screencap -p", encoding=None)
pathlib.Path("p.png").write_bytes(png_data)

Transfer files

d.sync.push(b"Hello Android", "/data/local/tmp/hi.txt") # 推送二进制文本
d.sync.push(io.BytesIO(b"Hello Android"), "/data/local/tmp/hi.txt") # 推送可读对象Readable object
d.sync.push("/tmp/hi.txt", "/data/local/tmp/hi.txt") # 推送本地文件
d.sync.push(pathlib.Path("/tmp/hi.txt"), "/data/local/tmp/hi.txt") # 推送本地文件

# 读取文件
for chunk in d.sync.iter_content("/data/local/tmp/hi.txt"):
    print("Chunk", chunk)

d.sync.push(b"Hello world", "/data/local/tmp/hi.txt")
output = d.sync.read_text("/data/local/tmp/hi.txt", encoding="utf-8")
# Expect output: "Hello world"
output = d.sync.read_bytes("/data/local/tmp/hi.txt")
# Expect output: b"Hello world"

# 拷贝到本地
d.sync.pull("/data/local/tmp/hi.txt", "hi.txt")

# 获取包的信息
info = d.app_info("com.example.demo")
if info:
    print(info) 
	# output example:
    # {
	# "version_name": "1.2.3", "version_code": "12", "signature": "0xff132", 
    # "first_install_time": datetime-object, "last_update_time": datetime-object,
    # }

Extended Functions

AdbUtils provided some custom functions for some complex operations.

You can use it like this:

# save screenshot
pilimg = d.screenshot()
pilimg.save("screenshot.jpg")

# get current app info
app_info = d.app_current()
print(app_info.package)
print(app_info.activity)
print(app_info.pid) # might be 0

# install apk
d.install("apidemo.apk") # use local path
d.install("http://example.com/apidemo.apk") # install from url
# raise AdbInstallError if something went wrong

# simulate click
d.click(100, 100)
d.click(0.5, 0.5) # center, should be float and <= 1.0

# swipe from(10, 10) to(200, 200) 500ms
d.swipe(10, 10, 200, 200, 0.5)

d.list_packages()
# example output: ["com.example.hello"]

d.window_size()
# example output: (1080, 1920)

d.rotation()
# example output: 1
# other possible valus: 0, 1, 2, 3

d.app_info("com.github.uiautomator")
# example output: {"version_name": "1.1.7", "version_code": "1007"}

d.keyevent("HOME")
d.volume_up()
d.volume_down()
d.volume_mute()

d.send_keys("hello world$%^&*") # simulate: adb shell input text "hello%sworld\%\^\&\*"

d.open_browser("https://www.baidu.com") # 打开百度
# There still too many functions, please see source codes

# check if screen is on
d.is_screen_on() # 返回屏幕是否亮屏 True or False

# adb root
d.root()

# adb tcpip <port>
d.tcpip(5555)

Screenrecord (mp4)

d.start_recording("video.mp4")
time.sleep(5)
d.stop_recording()

Logcat

# filter logcat to file
logcat = d.logcat("logcat.txt", clear=True, re_filter=".*FA.*") # clear default False
# do something else
logcat.stop(timeout=3) # tell thread to stop write, wait for 3s, if not stopped, raise TimeoutError
logcat.stop_nowait() # tell thread to stop write and close file

Screenrecord will try to use scrcpy first if scrcpy found in $PATH, then fallback to adb shell screenrecord

Note: The old method d.screenrecord() is removed after 0.16.2

For further usage, please read _device.py for details.

Run in command line 命令行使用

# List devices
$ python -m adbutils -l
8d1f93be              MI 5s
192.168.190.101:5555  Google Nexus 5X - 7.0.0 - API 24 - 1080x1920

# Show adb server version
$ python -m adbutils -V
39

# Install apk from local filesystem 安装本地apk(带有进度)
$ python -m adbutils -i some.apk
# Install apk from URL 通过URL安装apk(带有进度)
$ python -m adbutils -i http://example.com/some.apk
# Install and launch (-L or --launch)
$ python -m adbutils -i http://example.com/some.apk -L

# Parse apk info (support URL and local)
$ python -m adbutils --parse http://example.com/some.apk
$ python -m adbutils --parse some.apk
package: com.example.some
main-activity: com.example.some.MainActivity
version-name: 1.0.0
version-code: 100

# Uninstall 卸载应用
$ python -m adbutils -u com.github.example

# Push
$ python -m adbutils --push local.txt:/sdcard/remote.txt

# Pull
$ python -m adbutils --pull /sdcard/remote.txt # save to ./remote.txt

# List installed packages 列出所有应用
$ python -m adbutils --list-packages
com.android.adbkeyboard
com.buscode.whatsinput
com.finalwire.aida64
com.github.uiautomator

# Show URL of file QRCode 
$ python -m adbutils --qrcode some.apk
.--------.
|        |
| qrcode |
|        |
\--------/

# screenshot with screencap
$ python -m adbutils --screenshot screen.jpg 

# download minicap, minicap.so to device
$ python -m adbutils --minicap

# take screenshot with minicap
$ python -m adbutils --minicap --screenshot screen.jpg # screenshot with minicap

# Show more info for developers
$ python -m adbutils --dump-info
==== ADB Info ====
Path: /usr/local/bin/adb
Server version: 41

>> List of devices attached
- 9de75303 picasso Redmi K30 5G

# Track device status, function like: watch adb devices
$ python -m adbutils --track
15:09:59.534 08a3d291 -> device
15:10:02.683 08a3d291 -> absent
15:10:05.196 08a3d291 -> offline
15:10:06.545 08a3d291 -> absent
15:10:06.545 08a3d291 -> device

Environment variables

ANDROID_SERIAL  serial number to connect to
ANDROID_ADB_SERVER_HOST adb server host to connect to
ANDROID_ADB_SERVER_PORT adb server port to connect to

Color Logcat

For convenience of using logcat, I put put pidcat inside.

python3 -m adbutils.pidcat [package]

Experiment

Install Auto confirm supported(Beta), you need to famillar with uiautomator2 first

# Install with auto confirm (Experiment, based on github.com/openatx/uiautomator2)
$ python -m adbutils --install-confirm -i some.apk

For more usage, please see the code for details.

Examples

Record video using screenrecord

stream = d.shell("screenrecord /sdcard/s.mp4", stream=True)
time.sleep(3) # record for 3 seconds
with stream:
	stream.send(b"\003") # send Ctrl+C
	stream.read_until_close()

start = time.time()
print("Video total time is about", time.time() - start)
d.sync.pull("/sdcard/s.mp4", "s.mp4") # pulling video

Reading Logcat

d.shell("logcat --clear")
stream = d.shell("logcat", stream=True)
with stream:
    f = stream.conn.makefile()
    for _ in range(100): # read 100 lines
        line = f.readline()
        print("Logcat:", line.rstrip())
    f.close()

Develop

git clone https://github.com/openatx/adbutils adbutils
pip3 install -e adbutils # install as development mode

Now you can edit code in adbutils and test with

import adbutils
# .... test code here ...

Run tests requires one device connected to your computer

# change to repo directory
cd adbutils

pip3 install pytest
pytest tests/

Environment

Some environment can affect the adbutils behavior

  • ADBUTILS_ADB_PATH: specify adb path, default search from PATH
  • ANDROID_SERIAL: default adb serial
  • ANDROID_ADB_SERVER_HOST: default 127.0.0.1
  • ANDROID_ADB_SERVER_PORT: default 5037

Watch adb socket data

Watch the adb socket data using socat

$ socat -t100 -x -v TCP-LISTEN:5577,reuseaddr,fork TCP4:localhost:5037

open another terminal, type the following command then you will see the socket data

$ export ANDROID_ADB_SERVER_PORT=5577
$ adb devices

Changes from 1.x to 2.x

Remove

  • current_app removed, use app_current instead
  • package_info is going to remove, use app_info instead

Add

  • add volume_up, volume_down, volume_mute

Generate TOC

gh-md-toc --insert README.md

https://github.com/ekalinin/github-markdown-toc

Thanks

Alternative

Ref

LICENSE

MIT

adbutils's People

Contributors

clchrlls avatar codeskyblue avatar dependabot-preview[bot] avatar everytian avatar gianttreelp avatar legolas-li avatar leng-yue avatar linw1995 avatar mhils avatar pythontryhard avatar reenignearcher avatar rokm avatar srdr0p avatar vccabral avatar xiaojun0822 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

adbutils's Issues

adb pull command not work

command "adb shell screencap -p > 1.png" can work in terminal,but can not work with d.shell("screencap -p > 1.png")...
And,d.shell("screencap -p /sdcard/1.png") works,BUT d.shell("pull /sdcard/1.png 1.png")

Apk的“version_name”如果是“字母+数字”会返回空结果

d.package_info('com.ksxx.forestmonitoring')

{'package_name': 'com.ksxx.forestmonitoring', 'version_name': '', 'version_code': '38', 'flags': ['HAS_CODE', 'ALLOW_CLEAR_USER_DATA', 'ALLOW_BACKUP'], 'first_install_time': datetime.datetime(2021, 6, 9, 18, 54, 13), 'last_update_time': datetime.datetime(2021, 6, 9, 18, 54, 13), 'signature': 'aed60245'}

aapt dump badging YueLinJianCe.apk
package: name='com.ksxx.forestmonitoring' versionCode='38' versionName='forest_1.7.7' compileSdkVersion='29' compileSdkVersionCodename='10'

adb.sync.push(src,dst)不生效

我的命令如下:
adb_device = adbutils.AdbClient(host=params.adbIP, port=params.adbPort).device()
adb_device.sync.push('本地的二进制文件', '设备的路径文件')

问题:
失败原因不知道

如果我推送,这样子貌似可以
adb_device.sync.push(b'本地的二进制文件内容', '设备的路径文件')

Screen record error

I'm using the below code block:

r = d.screenrecord(no_autostart=True)
r.start() # start record
r.stop_and_pull("video.mp4") # stop recording and pull video to local, then remove video from device

but when I stop recording I'm getting this error:
Traceback (most recent call last):
File "C:\Users...\main.py", line 277, in on_click_record
self.r.stop_and_pull("~/Desktop/video.mp4")
File "C:\Users...\Python39\site-packages\adbutils\mixin.py", line 565, in stop_and_pull
self.stop()
File "C:\Users...\Python39\site-packages\adbutils\mixin.py", line 558, in stop
self._stream.send("\003")
AttributeError: '_AdbStreamConnection' object has no attribute 'send'

Any help on this would be appreciated.

指定 ADB 可执行文件路径的方法?

使用 PyInstaller 打包时未能将 binaries 文件夹内容打包到产物里,导致运行时出现 No adb exe could be found 错误。
不知道是否能提供一个初始化参数来指定一个自定义的 adb 可执行文件路径呢?

adbutils.errors.AdbError: rotation get failed

Script:
import adbutils
devide=adbutils.AdbClient(host="127.0.0.1",port=5037)
d=devide.device_list()[0]
#print(d.is_screen_on())
print(d.current_app())
d.app_start("com.android.launcher3")
d.rotation()

Error:
Traceback (most recent call last):
File "G:/MyPython/MyAirTest/V500/adb的代码库测试.py", line 12, in
d.rotation()
File "C:\Program Files\Python38\lib\site-packages\adbutils\mixin.py", line 292, in rotation
raise AdbError("rotation get failed")
adbutils.errors.AdbError: rotation get failed

The ability of get shell command output should be enhanced.

if we want to get current Activity,
we can get from by this shell command->dumpsys activity | grep -w ResumedActivity
but ,failed.

print(d.shell_output("dumpsys activity |grep -w ResumedActivity"))
/system/bin/sh: dumpsys activity |grep -w ResumedActivity: not found

example:

adb shell
W-P311:/ $ dumpsys activity |grep -w ResumedActivity
ResumedActivity: ActivityRecord{b11e81c u0 com.tencent.mobileqq/.activity.SplashActivity t12623}
W-P311:/ $

Download adb binaries directly from android.com

This is a feature request to download and extract the adb binaries directly from android.com during setup, instead of from your other repo (https://github.com/openatx/adb-binaries). The binaries in that repo have been outdated since at least April 2020 (when wireless pairing was introduced).

windows: https://dl.google.com/android/repository/platform-tools-latest-windows.zip

mac: https://dl.google.com/android/repository/platform-tools-latest-darwin.zip

linux: https://dl.google.com/android/repository/platform-tools-latest-linux.zip

adbutil 0.16.0 screenrecord录屏有问题

######## 看了一下源码,是push的脚本名称和运行的脚本名称不一致导致的,希望能修改一下

screenshot_3

######## 另外还有个问题,对于手机内没有内置screenrecord如何实现录屏呢(比如华为手机和某些android机型),能用提供minicap录屏的通用接口呢?

Screenrecord not stopping

For some reason it seems that the stop() method on the ScreenRecord class does not work. After sending a stop_and_pull call the function hangs until the 3 min timeout on the read_until_close step.

To reproduce:

import time
from adbutils import adb

device = adb.device()
recording = device.screenrecord(remote_path="/data/local/tmp/foo.mp4") 
time.sleep(5)
recording.stop_and_pull("foo.mp4")

This should take around 5 seconds to run, but takes a little over 3 minutes

'AdbConnection' isn't found in adbutils?

So according to #46 (comment) '_AdbStreamConnection' was removed from 'adbutils'. However, when removing and replacing with 'AdbConnection'.

Error Message:
Traceback (most recent call last): File "src/main.py", line 1, in <module> import scrcpy File "/mnt/c/Users/shiba/OneDrive/Documents/Mirror/src/scrcpy/__init__.py", line 6, in <module> from .core import Client File "/mnt/c/Users/shiba/OneDrive/Documents/Mirror/src/scrcpy/core.py", line 11, in <module> from adbutils import AdbDevice, AdbError, Network, AdbConnection, adb ImportError: cannot import name 'AdbConnection' from 'adbutils' (/home/poka/.local/lib/python3.8/site-packages/adbutils/__init__.py)

push 失败,再次push,传输速度会变得很慢

push的时候手机空间不足安装失败了,再次push,上传速度就超级慢,无论是换台手机还是换个文件,都一样,重启adb也是很卡,只有重启进程才恢复正常
暂时是把0.14.1的push代码考到0.11.0下使用
运行环境是win10
image

Permission denied: 'git' when installing

Issue:

I am getting per "error: [Errno 13] Permission denied: 'git'" when I run pip install adbutils

OS:

Distributor ID: Ubuntu
Description: Ubuntu 20.04.1 LTS
Release: 20.04
Codename: focal

Error log:

Building wheels for collected packages: adbutils
Building wheel for adbutils (setup.py) ... error
ERROR: Command errored out with exit status 1:
command: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/var/tmp/pip-install-d1c4tyzw/adbutils_cd3060821fbb4327b2a3bc27d37c0b4f/setup.py'"'"'; file='"'"'/var/tmp/pip-install-d1c4tyzw/adbutils_cd3060821fbb4327b2a3bc27d37c0b4f/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d /var/tmp/pip-wheel-j5cai2yg
cwd: /var/tmp/pip-install-d1c4tyzw/adbutils_cd3060821fbb4327b2a3bc27d37c0b4f/
Complete output (24 lines):
setup.py arguments: ['/var/tmp/pip-install-d1c4tyzw/adbutils_cd3060821fbb4327b2a3bc27d37c0b4f/setup.py', 'bdist_wheel', '-d', '/var/tmp/pip-wheel-j5cai2yg']
running bdist_wheel
running build
running build_py
creating build
creating build/lib
creating build/lib/adbutils
copying adbutils/_utils.py -> build/lib/adbutils
copying adbutils/errors.py -> build/lib/adbutils
copying adbutils/pidcat.py -> build/lib/adbutils
copying adbutils/main.py -> build/lib/adbutils
copying adbutils/init.py -> build/lib/adbutils
copying adbutils/mixin.py -> build/lib/adbutils
running egg_info
writing adbutils.egg-info/PKG-INFO
writing dependency_links to adbutils.egg-info/dependency_links.txt
writing requirements to adbutils.egg-info/requires.txt
writing top-level names to adbutils.egg-info/top_level.txt
[pbr] Reusing existing SOURCES.txt
creating build/lib/adbutils/binaries
copying adbutils/binaries/README.md -> build/lib/adbutils/binaries
installing to build/bdist.linux-x86_64/wheel
running install
error: [Errno 13] Permission denied: 'git'

ERROR: Failed building wheel for adbutils
Running setup.py clean for adbutils
Failed to build adbutils
Installing collected packages: adbutils
Running setup.py install for adbutils ... error
ERROR: Command errored out with exit status 1:
command: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/var/tmp/pip-install-d1c4tyzw/adbutils_cd3060821fbb4327b2a3bc27d37c0b4f/setup.py'"'"'; file='"'"'/var/tmp/pip-install-d1c4tyzw/adbutils_cd3060821fbb4327b2a3bc27d37c0b4f/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /var/tmp/pip-record-8xp3owcn/install-record.txt --single-version-externally-managed --user --prefix= --compile --install-headers /home/i_am_user/.local/include/python3.8/adbutils
cwd: /var/tmp/pip-install-d1c4tyzw/adbutils_cd3060821fbb4327b2a3bc27d37c0b4f/
Complete output (3 lines):
setup.py arguments: ['/var/tmp/pip-install-d1c4tyzw/adbutils_cd3060821fbb4327b2a3bc27d37c0b4f/setup.py', 'install', '--record', '/var/tmp/pip-record-8xp3owcn/install-record.txt', '--single-version-externally-managed', '--user', '--prefix=', '--compile', '--install-headers', '/home/i_am_user/.local/include/python3.8/adbutils']
running install
error: [Errno 13] Permission denied: 'git'
----------------------------------------
ERROR: Command errored out with exit status 1: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/var/tmp/pip-install-d1c4tyzw/adbutils_cd3060821fbb4327b2a3bc27d37c0b4f/setup.py'"'"'; file='"'"'/var/tmp/pip-install-d1c4tyzw/adbutils_cd3060821fbb4327b2a3bc27d37c0b4f/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /var/tmp/pip-record-8xp3owcn/install-record.txt --single-version-externally-managed --user --prefix= --compile --install-headers /home/i_am_user/.local/include/python3.8/adbutils Check the logs for full command output.

support adb connect

Some logs

[57480]: 001bhost:connect:102.2.2.3:4433
[ 5037]: OKAY
[ 5037]: 0023failed to connect to 102.2.2.3:4433
[proxy] ('127.0.0.1', 5037) has disconnected
[proxy] ('127.0.0.1', 57480) has disconnected, too

Fix README.md change devices() -> device_list()

README.md tells me that to list all the devices connected i have to adb.devices().
But this raises an erorr:

adb.devices()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [3], in <cell line: 1>()
----> 1 adb.devices()

AttributeError: 'AdbClient' object has no attribute 'devices'

I've tried help(adb) and found device_list method, which listed all the devices connected.
So, I suggest updating README.md https://github.com/openatx/adbutils#list-all-the-devices-and-get-device-object

Screenshot without saving.

Is it possible to get binary screenshot data directly from the phone’s memory, without saving to the phone’s SD card and then saving it to local storage?

ScreenRecord stop() 会卡住

self._stream.read_until_close()

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/adbutils/mixin.py", line 461, in stop_and_pull
    self.stop()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/adbutils/mixin.py", line 455, in stop
    self._stream.read_until_close()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/adbutils/__init__.py", line 137, in read_until_close
    chunk = self.read_raw(4096)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/adbutils/__init__.py", line 112, in read_raw
    chunk = self.conn.recv(t)
KeyboardInterrupt

卡在这

手机:OPPO R15 android8
PC:MacBook pro

Random adb ports in Android 11+

In Android 11 it appears to choose a random ADB port (from what I've seen between 30000 and 50000)... what's the best way to find the port number from python?

This might not be all devices, but it's what I've observed on Pixel 3 and 2.

adb push failed on windows

adbutils==1.0.2

use like:
device.push("resource/Gallery/AutoTest/A_GIF/rain.gif", "/storage/emulated/0/DCIM/")
return error

Command ''D:\python_workspace\TestKit\venv\lib\site-packages\adbutils\binaries\adb.exe' -s 6a6b10bd push resource/Gallery/. /storage/emulated/0/DCIM/' returned non-zero exit status 1.

push source code:
self.adb_output("push", local, remote)

adb_output -> list2cmdline -> map(shlex.quote, args)

shlex.quote will convert 'D:\\python_workspace\\TestKit\\venv\\lib\\site-packages\\adbutils\\binaries\\adb.exe' to '\'D:\\python_workspace\\TestKit\\venv\\lib\\site-packages\\adbutils\\binaries\\adb.exe\'' , this will lead this error

image

Hangs on adb.device_list ()

Hello, when I try to get a list of devices using the adb.device_list command, my script freezes. With the help of debug mode, I realized that adbutils hangs in this function:

    def iter_device(self):
        """
        Returns:
            iter of AdbDevice
        """
        with self._connect() as c:
            c.send("host:devices")
            c.check_okay()
            output = c.read_string()
            for line in output.splitlines():
                parts = line.strip().split("\t")
                if len(parts) != 2:
                    continue
                if parts[1] == 'device':
                    yield AdbDevice(self, parts[0])

But more specifically, then on this line c.check_okay()
What could be the problem?

adb命令

Can the adb command simulate the enter key or search key? . such as
device.press.enter ()
device.press.search (), similar to uiautomator, can simulate a carriage return, search,
If so what is the adb command? Look forward to your answer

when install apks in threading ,there is an adbInstallError happend.

Exception in thread Thread-2:
Traceback (most recent call last):
File "D:\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "D:\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "G:/MyPython/Studty/65-多媒体-图片操作/21 循环重启判断systemui Launcher是否正常显示.py", line 116, in install
device.install(apk_path=apk_loaction)
File "D:\Python36\lib\site-packages\adbutils\mixin.py", line 126, in install
self.install_remote(dst, clean=True)
File "D:\Python36\lib\site-packages\adbutils\mixin.py", line 144, in install_remote
raise AdbInstallError(output)
adbutils.errors.AdbInstallError: cmd: Failure calling service package: Broken pipe (32)

divide by zero using APK install()

A divide by zero happens when using install() function to install a small APK. When the time to copy the APK is less than a second 'copytime' becomes zero:

copytime = time.time() - self.start_time
speed = humanize(self.copied / copytime) + "/s"

在反复连接设备时,同一设备sn号会改变

code:

import adbutils

adb = adbutils.AdbClient(host="127.0.0.1", port=5037)
for event in adb.track_devices():
print(event.present, event.serial, event.status)

result:
True WRU6R20603000237 offline
False WRU6R20603000237 absent
True WRU6R20603000237 device
False WRU6R20603000237 absent
True WRU6R20603000237 offline
False WRU6R20603000237 absent
True WRU6R20603000237 device
False WRU6R20603000237 absent
True WRU6R20603000237 offline
False WRU6R20603000237 absent
True WRU6R20603000237 device
False WRU6R20603000237 absent
True c69d9b9f9ac7175b offline
False c69d9b9f9ac7175b absent

True WRU6R20603000237 offline
False WRU6R20603000237 absent
True WRU6R20603000237 device
False WRU6R20603000237 absent
True WRU6R20603000237 offline
False WRU6R20603000237 absent
True WRU6R20603000237 device

adb_output() 方法,问题请教

def adb_output(self, *args, **kwargs):
        """Run adb command use subprocess and get its content

        Returns:
            string of output

        Raises:
            EnvironmentError
        """

        cmds = [adb_path(), '-s', self._serial
                ] if self._serial else [adb_path()]
        cmds.extend(args)
        cmdline = subprocess.list2cmdline(map(str, cmds))

        try:
            return subprocess.check_output(cmdline,
                                           stderr=subprocess.STDOUT,
                                           shell=True).decode('utf-8')
        except subprocess.CalledProcessError as e:
            if kwargs.get('raise_error', True):
                raise EnvironmentError(
                    "subprocess", cmdline,
                    e.output.decode('utf-8', errors='ignore'))

使用 adbutils 过程中,要使用 adb logcat -c 这样的命令,所以找到了 adb_output() 这个函数,但是发现他的传参是通过 args 接收的,调用: adb_output("logcat", "-c"),这样感觉比较麻烦呀;

直接实现成类似 shell() 的调用方式:adb_output("logcat -c") 会更方便一些,请教下。

报错:AttributeError: module 'retry' has no attribute 'retry'

import adbutils

d = adbutils.AdbClient(host="127.0.0.1", port=5037)

我在调试这句代码时,报了下面的错误:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/lenovo/Desktop/camera_factory _auto_test/untils/demo.py", line 2, in <module>
    from adbutils import adb
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "C:\python_env\camera_factory _case\lib\site-packages\adbutils\__init__.py", line 23, in <module>
    from adbutils.mixin import ShellMixin
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "C:\python_env\camera_factory _case\lib\site-packages\adbutils\mixin.py", line 11, in <module>
    from retry import retry
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "C:\python_env\camera_factory _case\lib\site-packages\retry\__init__.py", line 5, in <module>
    from .api import retry
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "C:\python_env\camera_factory _case\lib\site-packages\retry\api.py", line 7, in <module>
    from retry.compat import decorator
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "C:\python_env\camera_factory _case\lib\site-packages\retry\compat.py", line 5, in <module>
    from decorator import decorator
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "C:\Users\lenovo\Desktop\camera_factory _auto_test\untils\decorator.py", line 9, in <module>
    import wda
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "C:\python_env\camera_factory _case\lib\site-packages\wda\__init__.py", line 260, in <module>
    class BaseClient(object):
  File "C:\python_env\camera_factory _case\lib\site-packages\wda\__init__.py", line 383, in BaseClient
    @retry.retry(exceptions=WDAEmptyResponseError, tries=3, delay=2)
AttributeError: module 'retry' has no attribute 'retry'

Add support for emu command

I would like to be able to send sensor data to the emulator. From command line I can use something like this to simulate, for example, a 1 second device shake:

adb emu sensor set acceleration 100:100:100; sleep 1; adb emu sensor set acceleration 0:0:0

It would be nice to be able to use adbutils to send this emu commands.

is it support code to run "screencap -p"?

the device is connected, when run i get this, please help, thx :D

from adbutils import adb

out = adb.connect("127.0.0.1:62026")
d = adb.device()
return d.adb_output("screencap -p")
Traceback (most recent call last):
  File "D:\App\Python\Python37-32\lib\site-packages\adbutils\__init__.py", line 312, in adb_output
    return subprocess.check_output(cmdline, stderr=subprocess.STDOUT, shell=True).decode('utf-8')
  File "D:\App\Python\Python37-32\lib\subprocess.py", line 395, in check_output
    **kwargs).stdout
  File "D:\App\Python\Python37-32\lib\subprocess.py", line 487, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command 'D:\App\Android\SDK\platform-tools\adb.EXE -s 127.0.0.1:62026 "screencap -p"' returned non-zero exit status 1.

Screenrecord Error

import time
from adbutils import adb

d = adb.device()

rec = d.screenrecord(remote_path="/data/local/tmp/cu.mp4")
time.sleep(5)
rec.stop_and_pull("fc.mp4")

The result:

AttributeError: '_AdbStreamConnection' object has no attribute 'send'

How to monitor specific devices?

I have two or more devices connected to my computer, and I want to monitor a specific one. How can I achieve this? Can I use track_devices()?
thanks

Error while pushing file to phone.

So I was using Adbutils. However, I face an error while pushing a file onto an android:

OSError: [Errno subprocess] 'C:\Users\shiba\AppData\Local\Programs\Python\Python310\lib\site-packages\adbutils\binaries\adb.exe' -s N9XDU17207002827 push 'c:\Users\shiba\Documents\Mirror\src\scrcpy\scrcpy-server-v1.24.jar' /data/local/tmp/: 'The filename, directory name, or volume label syntax is incorrect.\r\n'

I first thought the files were just not there, but I'm fairly confident that the file exists.
Here is the code I'm running:

jar_name = "scrcpy-server-v1.24.jar"
        server_file_path = os.path.join(
            os.path.abspath(os.path.dirname(__file__)), jar_name
        )
        self.device.push(server_file_path, "/data/local/tmp/")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.