懶人的python——一次執行多條linux命令
阿新 • • 發佈:2018-12-24
今天在公司搞了半天EE2I,一直在敲相同的命令累死了。每次執行ee2i.sh temp命令後,都要到cd到某個目錄下執行下一個shell指令碼。做完一次後又要刪除臨時檔案。總之,重複工作很多,我的指甲都敲累了。所以晚上回到家就寫了個類似的python指令碼來自動化執行這些討厭的重複工作,也順便多學點python的知識。
- import os
- import sys
- import shutil
- import subprocess
- if __name__ == '__main__':
- e2iDir = 'e2i'
- tempFileName = 'temp'
- tempDir = os.path.join(e2iDir, tempFileName)
- lintResultDir = 'lintResult'
- if os.path.exists(tempDir):
- shutil.rmtree(tempDir)
- else:
- #Only for test
- os.mkdir(tempDir)
- if os.path.exists(lintResultDir):
- shutil.rmtree(lintResultDir)
- else:
- #Only for test
- os.mkdir(lintResultDir)
- # The commands to excute
- ee2iCmd = ['./product/bin/testapp', tempFileName]
- lintCmd = ['ls', '-R'] #XLINT_XXXX.sh
- cmdList = []
- cmdList.append(ee2iCmd)
- cmdList.append(lintCmd)
- # Run all commands once.
- for oscmd in cmdList:
- 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)