+++++++++++++++++++++++++++++python
python執行shell命令
1 os.systemshell
能夠返回運行shell命令狀態,同時會在終端輸出運行結果app
例如 ipython中運行以下命令,返回運行狀態status函數
os.system('python -V') os.system('tree')
2 os.popen()ui
能夠返回運行結果code
import os r = os.popen('python -V').read() print(type(r)) print(r)
或者blog
In [20]: output = os.popen('cat /proc/cpuinfo') In [21]: lineLen = [] In [22]: for line in output.readlines(): lineLen.append(len(line)) ....: In [23]: line line lineLen In [23]: lineLen Out[23]: [14, 25, ...
3 commands.getstatusoutput('cat /proc/cpuinfo')進程
如何同時返回結果和運行狀態,commands模塊:ip
import commands (status, output) = commands.getstatusoutput('cat /proc/cpuinfo') In [25]: status Out[25]: 0 In [26]: len(output) Out[26]: 3859
4 subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE)get
使用模塊subprocess
一般項目中常用方法爲subporcess.Popen, 咱們能夠在Popen()創建子進程的時候改變標準輸入、標準輸出和標準錯誤,並能夠利用subprocess.PIPE將多個子進程的輸入和輸出鏈接在一塊兒,構成管道(pipe):
import subprocess child1 = subprocess.Popen("tree",shell=True, stdout=subprocess.PIPE) out = child1.stdout.read() print(out.decode('gbk'))
import subprocess child1 = subprocess.Popen("tree /F".split(),shell=True, stdout=subprocess.PIPE) out = child1.stdout.read() print(out.decode('gbk'))
import subprocess child1 = subprocess.Popen(['tree','/F'].split(),shell=True, stdout=subprocess.PIPE) out = child1.stdout.read() print(out.decode('gbk'))
退出進程
size_str = os.popen('adb shell wm size').read() if not size_str: print('請安裝 ADB 及驅動並配置環境變量') sys.exit()
封裝好的函數:Python執行shell命令
from subprocess import Popen, PIPE def run_cmd(cmd): # Popen call wrapper.return (code, stdout, stderr) child = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True) out, err = child.communicate() ret = child.wait() return (ret, out, err) if __name__ == '__main__': r=run_cmd("dir") print(r[0]) print(r[1].decode("gbk")) print(r[2])