懒人的python——一次执行多条linux命令

xiaoxiao2022-06-11  33

今天在公司搞了半天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)  

转载请注明原文地址: https://www.6miu.com/read-4932158.html

最新回复(0)