python批量执行linux命令并写入log日志
生活随笔
收集整理的這篇文章主要介紹了
python批量执行linux命令并写入log日志
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
linux下使用python運行make命令并把日志有錯的路徑寫入.log日志中
#!/usr/bin/python # -*- coding: UTF-8 -*- import subprocess import sys import os import time import glob # 所有可執行文件 # rootdir = '/home/test/' rootdir = raw_input("可執行文件根目錄:") errorDir = '/home/' paths = [] errorPaths = [] # 開始方法 def runPath(index):# 進入目錄cd = "cd %s;" %paths[index]# 執行的命令行命令cmd = "%s make" %cd# 執行命令并返回執行p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)# 循環輸出執行行for line in p.stdout.readlines():print line# 執行結果retval = p.wait()print "執行結果:", retval# 文件下所有df文件df_list = glob.glob(paths[index] + "/*.df")for df_item in df_list:retval = os.path.getsize(df_item)print "文件路徑:%s 執行結果:%s" %(df_item,retval)# 文件下所有df文件大小if retval > 0:errorPaths.append(paths[index])breakdef run_1():# 從第一個開始循環print "----所有文件-------\n"count = 0while count < len(paths):print "-------------------------\n"# 執行方法runPath(count)count += 1# 打印輸出日志printError()def run_2():# 從第一個開始循環count = 0print "-------------------------\n"print "-1. 退出"while count < len(paths):# 執行方法print count,". ",paths[count],'\n'count += 1runLang = int(raw_input("請輸入要執行的文件:"))if runLang >= 0:runPath(runLang)# 打印輸出日志printError()else:close()def run_3():global errorDirerrorDir = raw_input("請輸入要存放的位置:")print "修改成功!"# 結束 def close():print "再見"sys.exit()# 開始 def play():# 初始化錯誤global errorPathserrorPaths = []print "---------- 歡迎進入執行系統 ---------------"print "1. 執行所有文件\n2. 執行指定文件\n3. 修改log日志默認位置\n0. 退出"runLang = raw_input("請輸入:")switch = {'1': run_1,'2': run_2,'3': run_3,'0': close}switch.get(runLang)()play()# 寫日志 def printError():print "%s,type:%s" %(errorDir,type(errorDir))datestr = time.strftime("%Y-%m-%d%H%M%S",time.gmtime())errlogpath = errorDir + datestr + "error.log"print errlogpath# errlogpath = "/home/zhangluhang/2021-0409110904error.log"f = open(errlogpath,'w+')for path in errorPaths:f.write("%s\r\n" % path)try:print 0except IOError:print "文件寫異常"else:f.close()# 執行獲取路徑 def root_paths():for root,dirs,files in os.walk(rootdir):# print dirsfor dir in dirs:# 獲取文件所屬目錄filePath = os.path.join(root,dir)paths.append(filePath)# 開始程序play()root_paths()總結
以上是生活随笔為你收集整理的python批量执行linux命令并写入log日志的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Win10怎么设置存储感知和删除临时文件
- 下一篇: 抖音是什么?抖音短视频怎么用