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

yipeiwu_com6年前Python基础

最近写脚本的时想要用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设计】。

相关文章

Python使用PyCrypto实现AES加密功能示例

本文实例讲述了Python使用PyCrypto实现AES加密功能。分享给大家供大家参考,具体如下: #!/usr/bin/env python from Crypto.Cipher...

解决PySide+Python子线程更新UI线程的问题

在我开发的系统,需要子线程去运行,然后把运行的结果发给UI线程,让UI线程知道运行的进度。 首先创建线程很简单 def newThread(self): d = Data() p...

Python的re模块正则表达式操作

这个模块提供了与 Perl 相似l的正则表达式匹配操作。Unicode字符串也同样适用。 正则表达式使用反斜杠" \ "来代表特殊形式或用作转义字符,这里跟Python的语法冲突,因此...

Python学习笔记之视频人脸检测识别实例教程

Python学习笔记之视频人脸检测识别实例教程

前言 上一篇博文与大家分享了简单的图片人脸识别技术,其实在实际应用中,很多是通过视频流的方式进行识别,比如人脸识别通道门禁考勤系统、人脸动态跟踪识别系统等等。 下面话不多说了,来一起看...

从零学Python之入门(五)缩进和选择

缩进 Python最具特色的是用缩进来标明成块的代码。我下面以if选择结构来举例。if后面跟随条件,如果条件成立,则执行归属于if的一个代码块。 先看C语言的表达方式(注意,这是C,不是...