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

最近写脚本的时想要用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命令并返回结果的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。