python執行命令行:python中執行shell命令行read結果


+++++++++++++++++++++++++++++

python執行shell命令
1 os.system  (只有這個方法是邊執行邊輸出,其他方法是最后一次性輸出)

可以返回運行shell命令狀態,同時會在終端輸出運行結果

例如 ipython中運行如下命令,返回運行狀態status

os.system('python -V')
os.system('tree')

 遇到亂碼問題可以采用一次性輸出來解決。https://www.cnblogs.com/andy9468/p/8418649.html

 或者pycharm的亂碼問題:https://www.cnblogs.com/andy9468/p/12766382.html

 

2 os.popen()

可以返回運行結果

import os

r = os.popen('python -V').read()
print(type(r))
print(r)

  

或者

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模塊:

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)

使用模塊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])

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM