1. 程式人生 > >懶人的python——一次執行多條linux命令

懶人的python——一次執行多條linux命令

今天在公司搞了半天EE2I,一直在敲相同的命令累死了。每次執行ee2i.sh temp命令後,都要到cd到某個目錄下執行下一個shell指令碼。做完一次後又要刪除臨時檔案。總之,重複工作很多,我的指甲都敲累了。所以晚上回到家就寫了個類似的python指令碼來自動化執行這些討厭的重複工作,也順便多學點python的知識。

  1. import os  
  2. import sys  
  3. import shutil  
  4. import subprocess  
  5. if __name__ == '__main__':  
  6.     e2iDir = 'e2i'  
  7.     tempFileName = 'temp'      
  8.     tempDir = os.path.join(e2iDir, tempFileName)  
  9.     lintResultDir = 'lintResult'  
  10.     if os.path.exists(tempDir):  
  11.         shutil.rmtree(tempDir)  
  12.     else:  
  13.         #Only for test  
  14.         os.mkdir(tempDir)         
  15.     if os.path.exists(lintResultDir):  
  16.         shutil.rmtree(lintResultDir)  
  17.     else:  
  18.         #Only for test  
  19.         os.mkdir(lintResultDir)  
  20.     # The commands to excute  
  21.     ee2iCmd = ['./product/bin/testapp', tempFileName]  
  22.     lintCmd = ['ls', '-R'] #XLINT_XXXX.sh  
  23.     cmdList = []  
  24.     cmdList.append(ee2iCmd)  
  25.     cmdList.append(lintCmd)  
  26.     # Run all commands once.  
  27.     for oscmd in cmdList:  
  28.         subprocess.call(oscmd)  

說明:

由於家裡沒有公司的開發環境,上面的這段程式碼只是個原型,主要是將幾條工作中要反覆執行的命令串起來執行。

總結:

1) 刪除包含子目錄的資料夾不能用os.rmdir(),而應該用shutil.rmtree();

2) subprocess.call()的入引數可以是個列表,列表的第一個元素代表命令字,後面的都是命令的引數;

3)使用os.path下的一個函式可以簡化路徑的操作,比如os.path.join連線路徑,os.path.exists()判斷某個檔案或路徑是否存在。

2 .不用  for 迴圈 

# coding: UTF-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')

import subprocess
import os
import commands

#os.system('cmd1 && cmd2')
cmd1 = "cd ../"
cmd2 = "ls"
cmd = cmd1 + " && " + cmd2

#如下兩種都可以執行
subprocess.Popen(cmd, shell=True)
subprocess.call(cmd,shell=True)