最近寫腳本的時想要用python直接在腳本中去執(zhí)行cmd命令,并且將返回值打印出來供下面調(diào)用,所以特意查了下,發(fā)現(xiàn)主要有一下幾種方式來實現(xiàn),很簡單:
就拿執(zhí)行adb, adb shell, adb devices 舉例
1.第一種方法 os 模塊的 os.sysytem()
import os os.system('adb)
執(zhí)行括號中系統(tǒng)命令,沒有返回值
2.第二種方法:os模塊的 os.popen()
if __name__=='__main__': import os a = os.popen('adb') #此時打開的a是一個對象,如果直接打印的話是對象內(nèi)存地址 text = a.read() #要用read()方法讀取后才是文本對象 print(text) a.close()#打印后還需將對象關(guān)閉 #下面執(zhí)行adb devices同理 b = os.popen('adb devices') text2 = b.read() print(text2) b.close()
下面是第二種方法的打印結(jié)果:
#adb返回的結(jié)果: 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 返回的結(jié)果: List of devices attached 740dc3d1 device
未完待續(xù)....
以下內(nèi)容為2019年5月更新
os.popen方法較os.system()而言是獲取控制臺輸出的內(nèi)容,那就用os.popen的方法了,popen返回的是一個file對象,跟open打開文件一樣操作了,r是以讀的方式打開,今天把寫法優(yōu)化了一下:
# coding:utf-8 import os # popen返回文件對象,跟open操作一樣 with os.popen(r'adb devices', 'r') as f: text = f.read() print(text) # 打印cmd輸出結(jié)果 # 輸出結(jié)果字符串處理 s = text.split("\n") # 切割換行 result = [x for x in s if x != ''] # 列生成式去掉空 print(result) # 可能有多個手機設(shè)備 devices = [] # 獲取設(shè)備名稱 for i in result: dev = i .split("\tdevice") if len(dev) >= 2: devices.append(dev[0]) if not devices: print('當前設(shè)備未連接上') else: print('當前連接設(shè)備:%s' % devices)
控制臺輸出如下:
以上這篇python腳本執(zhí)行CMD命令并返回結(jié)果的例子就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
