Python,ADB和Shell执行查询 [英] Python, adb and shell execution query
问题描述
我对Python不太熟悉,但对Ruby却很熟悉。因此,我将提供我想要实现的目标的类似物
I don't have a lot of familiarity with Python but I do with Ruby. So I will provide analogues for what I want to achieve
在Ruby中,我会
val = `adb devices`
获取存储的adb设备的原始输出在val中,并且
to get the "raw output" of adb devices stored in val, and
val=system("adb devices")
获取状态代码
我想在Python中执行相同的任务。我看着
I want to perform the same tasks in Python. I looked at
from subprocess import call
call(["adb devices"])
但是失败了,我不想使用os.system,因为我想得到一些适当的错误处理。我如何进行呼叫工作以及如何从Python中的反引号获取原始输出
but that failed, I don't want to use os.system cause I want to get some proper error handling. how do i make call work and how do i obtain raw output from backticks in Python
推荐答案
将命令和参数作为单独的元素传递列表中的内容:
Pass the command and arguments as separate elements of a list:
from subprocess import call
return_code = call(["adb", "devices"])
但是,这会将输出发送到stdout,您无法捕获它。相反,您可以使用 subprocess.check_ouput()
:
However, this sends the output to stdout and you can't capture it. Instead you can use subprocess.check_ouput()
:
from subprocess import check_output
adb_ouput = check_output(["adb", "devices"])
# stdout of adb in adb_output.
如果返回码非零,则会引发异常。您应该抓住它以查看返回码是什么。返回代码0不会引发异常:
If the return code is non-zero an exception is raised. You should catch it to see what the return code is. No exception is raised for return code 0:
from subprocess import check_output, CalledProcessError
try:
adb_ouput = check_output(["adb", "devices"])
except CalledProcessError as e:
print e.returncode
这篇关于Python,ADB和Shell执行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!