1. 程式人生 > 程式設計 >python中shell執行知識點

python中shell執行知識點

os.system

system方法會建立子程序執行外部程式,方法只返回外部程式的執行結果。這個方法比較適用於外部程式沒有輸出結果的情況。

import os
os.system('ls')

commands.getstatusoutput

使用commands模組的getoutput方法,這種方法同popend的區別在於popen返回的是一個檔案控制代碼,而本方法將外部程式的輸出結果當作字串返回,很多情況下用起來要更方便些。
主要方法:

  • commands.getstatusoutput(cmd) 返回(status,output)
  • commands.getoutput(cmd) 只返回輸出結果
  • commands.getstatus(file) 返回ls -ld file的執行結果字串,呼叫了getoutput,不建議使用此方法

當需要得到外部程式的輸出結果時,本方法非常有用。比如使用urllib呼叫Web API時,需要對得到的資料進行處理。os.popen(cmd) 要得到命令的輸出內容,只需再呼叫下read()或readlines()等 如a=os.popen(cmd).read()

import os
ls = os.popen('ls')
print ls.read()

commands.getstatusoutput

使用commands模組的getoutput方法,這種方法同popend的區別在於popen返回的是一個檔案控制代碼,而本方法將外部程式的輸出結果當作字串返回,很多情況下用起來要更方便些。

主要方法:

  • commands.getstatusoutput(cmd) 返回(status,output)
  • commands.getoutput(cmd) 只返回輸出結果
  • commands.getstatus(file) 返回ls -ld file的執行結果字串,呼叫了getoutput,不建議使用此方法
import commands
commands.getstatusoutput('ls -lt')   # 返回(status,output)

subprocess.call

根據Python官方文件說明,subprocess模組用於取代上面這些模組。有一個用Python實現的並行ssh工具—mssh,程式碼很簡短,不過很有意思,它線上程中呼叫subprocess啟動子程序來幹活。

from subprocess import call
call(["ls","-l"])
import shlex,subprocess
def shell_command(cmd,timeout) :
  data = {"rc":False,"timeout":False,"stdout":"","stderr":""}
  try :
    process = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    try:
      outs,errs = process.communicate(timeout=timeout)
      data["stdout"] = outs.decode("utf-8") 
      data["stderr"] = errs.decode("utf-8") 
      data["rc"] = True

    except subprocess.TimeoutExpired :
      process.kill()
      outs,errs = process.communicate()
      data["rc"] = False 
      data["stdout"] = outs.decode("utf-8") 
      data["stderr"] = "timeout"
      data["timeout"] = True 

  except Exception as e :
    data["rc"] = False 
    data["stderr"] = e 

  finally : 
    return data 

到此這篇關於python中shell執行知識點的文章就介紹到這了,更多相關python shell 執行內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!