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设计】。

相关文章

Django项目中添加ldap登陆认证功能的实现

最近在开发一个Django项目过程中,碰到了通过ldap认证用户登录的需求。由于之前都是自己写密码加密、用户登录等逻辑,连Django自带的认证模块都没用过,无奈网上关于django配置...

Python中出现IndentationError:unindent does not match any outer indentation level错误的解决方法

Python中出现IndentationError:unindent does not match any outer indentation level错误的解决方法

今天在网上copy的一段代码,代码很简单,每行看起来该缩进的都缩进了,运行的时候出现了如下错误:  【解决过程】  1.对于此错误,最常见的原因是,的确没有缩进。...

Python 对输入的数字进行排序的方法

要求,输入一串数字,并以列表的形式打印出来。 number = input('请输入一串数字:') print(number) print(type(number)) 假设输...

Python判断字符串是否为字母或者数字(浮点数)的多种方法

str为字符串s为字符串 str.isalnum() 所有字符都是数字或者字母 str.isalpha() 所有字符都是字母 str.isdigit() 所有字符都是数字 str.iss...

Django上线部署之IIS的配置方法

环境: 1 .Windows Server 2016 Datacenter 64位 2 .SQL Server 2016 Enterprise 64位 3 .Python 3.6.0 6...