利用Python 实现在文件目录遍历,依次将当前文件夹下子文件夹中的程序编译并自动运行,每一个子程序运行结束后,发送运行结束的提醒到指定邮箱。
想实现Python文件的后台运行,命令为:
nohup python -u myscript.py params1 > nohup.out 2>&1 & 其中参数 -u 为使得python不启用缓冲,可以及时将输出信息输出到 nohup.out 文件中。
python脚本程序自动后台运行后,该脚本调用的程序也会在后台运行,关闭当前终端不会kill程序。
1 1 import time 2 2 import os 3 3 import subprocess 4 4 import smtplib 5 5 from email.mime.text import MIMEText 6 6 7 7 8 8 def doSth(): 9 9 k=0 1010 while k < 30: 1111 time.sleep(5) 1212 k=k+1 1313 print('wake up') 1414 1515 def sendEmail(filename): 1616 _user="13956047103@163.com" 1717 _pwd="zxcvbnp" 1818 _to="lhailong@mail.ustc.edu.com" 1919 text="program in "+filename+"is finished!" 2020 msg=MIMEText(text) 2121 msg["Subject"]="program run result" 2222 msg["From"]=_user 2323 msg["To"]=_to 2424 2525 s=smtplib.SMTP("smtp.163.com",timeout=25) 2626 s.login(_user, _pwd) 2727 s.sendmail(_user, _to, msg.as_string()) 2828 s.close() 2929 3030 3131 k=0 3232 cwd=os.getcwd() 3333 for(folderName, subfolders, filenames) in os.walk('.'): 3434 print(k) 3535 k=k+1 3636 print('******************************************') 3737 print('current folder name: '+ folderName) 3838 if subfolders: 3939 print('subfolder:') 4040 print(subfolders) 4141 if filenames: 4242 print('sub file:') 4343 print(filenames) 4444 4545 runfile='./r_test.out' 4646 os.chdir(folderName) 4747 try: 4848 # os.system(folderName+'/make') 4949 myMake=subprocess.Popen('make') 5050 myMake.wait() 5151 runExe=subprocess.Popen(runfile) 5252 runExe.wait() 5353 # os.system(runfile) 5454 sendEmail(folderName) 5555 doSth() 5656 except: 5757 print('no exe in this file') 5858 print('******************************************') 5959 print('') 6060 os.chdir(cwd)