温馨提示×

python adb 命令怎样传输文件

小樊
81
2024-12-10 21:57:05
栏目: 编程语言

要使用Python ADB命令传输文件,您可以使用subprocess模块来执行ADB命令

import subprocess
import os

def push_file(local_file, remote_file):
    if not os.path.isfile(local_file):
        print(f"本地文件 {local_file} 不存在")
        return

    cmd = ['adb', 'push', local_file, remote_file]
    try:
        result = subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print(f"成功将文件从 {local_file} 推送到 {remote_file}")
        print(result.stdout.decode('utf-8'))
    except subprocess.CalledProcessError as e:
        print(f"推送文件失败: {e.stderr.decode('utf-8')}")

def pull_file(remote_file, local_file):
    cmd = ['adb', 'pull', remote_file, local_file]
    try:
        result = subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print(f"成功将文件从 {remote_file} 拉取到 {local_file}")
        print(result.stdout.decode('utf-8'))
    except subprocess.CalledProcessError as e:
        print(f"拉取文件失败: {e.stderr.decode('utf-8')}")

if __name__ == "__main__":
    local_file = "path/to/your/local/file.txt"
    remote_file = "/sdcard/remote_file.txt"

    push_file(local_file, remote_file)
    pull_file(remote_file, local_file)

在这个示例中,我们定义了两个函数:push_filepull_filepush_file函数将本地文件推送到设备的远程路径,而pull_file函数从设备的远程路径拉取文件到本地。

请确保将local_fileremote_file变量设置为正确的本地和远程文件路径。在执行此脚本之前,还需要确保已经安装了ADB并且设备已连接到计算机。

0