如何通过Python运行两个adbshell命令,但只存储一个命令的输出?

2024-09-28 03:16:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始在Windows7上使用Python2.7,我正在尝试合并adbshell命令来访问/更改Android设备上的目录。我需要做的是获取内部存储器中目录的大小,将输出保存为变量,然后删除该目录。根据我的研究,我认为我应该使用subprocess.Popen()来创建shell,然后使用.communicate()来发送所需的命令。但是我目前只能执行其中一个命令:删除目录。下面是我使用的代码:

 import os, subprocess
 from subprocess import PIPE, Popen

 adb_shell = subprocess.Popen('adb shell', stdin = subprocess.PIPE)
 adb_shell.communicate('cd /sdcard\nrm -r "Directory to Delete"\nexit\n')

但是,如果我通过执行以下操作添加另一个命令:

^{pr2}$

它不起作用,因为我需要合并stdout = subprocess.PIPE来存储du -sh "Directory A"命令的输出,但是我该怎么做呢?如果我像这样添加它:adb_shell = subprocess.Popen('adb shell', stdin = subprocess.PIPE, stdout = subprocess.PIPE),它就不起作用了。有什么建议吗?泰!在

编辑:我最接近的解决方案是:

    adb_shell = subprocess.Popen('adb shell', stdin = subprocess.PIPE, stdout = subprocess.PIPE)
    adb_shell.communicate('cd /sdcard\ndu -sh "qpython"\nexit\n')
    output = adb_shell.stdout
    print output

    adb_shell = subprocess.Popen('adb shell', stdin = subprocess.PIPE)
    adb_shell.communicate('cd /sdcard\nrm -r "qpython"\nexit\n')

其输出为:“”,模式“rb”位于0x02B4D910>;'


Tags: import命令目录stdinstdoutcdshellsubprocess
2条回答

虽然不漂亮,但很管用:

    lines = []
    get_restore_size = subprocess.Popen('adb shell du -sh /sdcard/qpython', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    for line in get_restore_size.stdout.readlines():
        lines.append(line)
        restore_size = (lines[0].strip('\t/sdcard/qpython\r\r\n'))
        print restore_size


    del_restore = subprocess.Popen('adb shell', stdin = subprocess.PIPE)
    del_restore.communicate('cd /sdcard\nrm -r "qpython"\nexit\n')

欢迎提出改进建议!在

没有理由在同一个shell会话中运行这两个命令:

print subprocess.check_output(["adb", "shell", "du -sh /sdcard/qpython"])
subprocess.check_output(["adb", "shell", "rm -r /sdcard/qpython"])

相关问题 更多 >

    热门问题