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中基本的日期时间处理的学习教程

Python中基本的日期时间处理的学习教程

Python程序能用很多方式处理日期和时间。转换日期格式是一个常见的例行琐事。Python有一个 time 和 calendar 模组可以帮忙。 什么是Tick? 时间间隔是以秒为单位的...

django数据模型(Model)的字段类型解析

字段类型(Field types) 1、AutoField 它是一个根据 ID 自增长的 IntegerField 字段。通常,你不必直接使用该字段。如果你没在别的字段上指定主 键,Dj...

python实战教程之自动扫雷

python实战教程之自动扫雷

前言 自动扫雷一般分为两种,一种是读取内存数据,而另一种是通过分析图片获得数据,并通过模拟鼠标操作,这里我用的是第二种方式。 一、准备工作 1.扫雷游戏 我是win10,没有默认的扫...

Python UnboundLocalError和NameError错误根源案例解析

如果代码风格相对而言不是那么的pythonic,或许很少碰到这类错误。当然并不是不鼓励使用一些python语言的技巧。如果遇到这这种类型的错误,说明我们对python中变量引用相关部分有...

在Python中处理字符串之ljust()方法的使用简介

 ljust()方法返回字符串左对齐的字符串长度宽度。填充是通过使用指定的fillchar(默认为空格)。如果宽度小于len(s)返回原始字符串。 语法 以下是ljust()方...