python脚本执行CMD命令并返回结果的例子

发布时间:2020-09-25 20:34:05 作者:xgh1951
来源:脚本之家 阅读:158

最近写脚本的时想要用python直接在脚本中去执行cmd命令,并且将返回值打印出来供下面调用,所以特意查了下,发现主要有一下几种方式来实现,很简单:

就拿执行adb, adb shell, adb devices 举例

1.第一种方法 os 模块的 os.sysytem()

import os

os.system('adb)

执行括号中系统命令,没有返回值

2.第二种方法:os模块的 os.popen()

if __name__=='__main__':
 import os 
 a = os.popen('adb')
 #此时打开的a是一个对象,如果直接打印的话是对象内存地址
 
 text = a.read()
 #要用read()方法读取后才是文本对象
 
 print(text)
 
 a.close()#打印后还需将对象关闭
 
 #下面执行adb devices同理
 b = os.popen('adb devices')
 text2 = b.read()
 print(text2)
 b.close()

下面是第二种方法的打印结果:

#adb返回的结果:
 
Android Debug Bridge version 1.0.40
Version 4986621
Installed as D:\androidsdk\platform-tools\adb.exe
 
global options:
 -a   listen on all network interfaces, not just localhost
 -d   use USB device (error if multiple devices connected)
 -e   use TCP/IP device (error if multiple TCP/IP devices available)
 -s SERIAL use device with given serial (overrides $ANDROID_SERIAL)
 -t ID  use device with given transport id
 -H   name of adb server host [default=localhost]
 -P   port of adb server [default=5037]
 -L SOCKET listen on given socket for adb server [default=tcp:localhost:5037]
 
general commands:
 devices [-l]    list connected devices (-l for long output)
 help      show this help message
 version     show version num
 
 
#adb devices 返回的结果:
List of devices attached
740dc3d1 device

未完待续....

以下内容为2019年5月更新

os.popen方法较os.system()而言是获取控制台输出的内容,那就用os.popen的方法了,popen返回的是一个file对象,跟open打开文件一样操作了,r是以读的方式打开,今天把写法优化了一下:

# coding:utf-8
import os
 
# popen返回文件对象,跟open操作一样
with os.popen(r'adb devices', 'r') as f:
 text = f.read()
print(text) # 打印cmd输出结果
 
# 输出结果字符串处理
s = text.split("\n") # 切割换行
result = [x for x in s if x != ''] # 列生成式去掉空
print(result)
 
# 可能有多个手机设备
devices = [] # 获取设备名称
for i in result:
 dev = i .split("\tdevice")
 if len(dev) >= 2:
  devices.append(dev[0])
 
if not devices:
 print('当前设备未连接上')
else:
 print('当前连接设备:%s' % devices)

控制台输出如下:

python脚本执行CMD命令并返回结果的例子

以上这篇python脚本执行CMD命令并返回结果的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

推荐阅读:
  1. Android--启动拍照功能并返回结果
  2. django如何执行原始查询sql并返回Dict字典例子

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python cmd 返回结果

上一篇:Vue实现带进度条的文件拖动上传功能

下一篇:testng的报告自定义笔记三

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》