繁体   English   中英

如何通过Python运行两个adb shell命令,但仅存储一个输出?

[英]How to run two adb shell commands via Python, but store output of only one?

我是Windows 7上使用Python 2.7的新手,并且尝试合并adb shell命令来访问/更改Android设备上的目录。 我需要做的是获取内部存储中目录的大小,将该输出另存为变量,然后删除该目录。 从我的研究中,我相信我应该使用subprocess.Popen()创建外壳,然后使用.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')

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

adb_shell.communicate('cd /sdcard\ndu -sh "Directory A"\nrm -r "Directory A"\nexit\n')

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

编辑:最接近解决方案的地方(实际上是在解释器中获取输出,然后再删除文件)是:

    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>'

它不是很漂亮,但是可以工作:

    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"])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM