利用Python 实现在文件目录遍历,依次将当前文件夹下子文件夹中的程序编译并自动运行,每一个子程序运行结束后,发送运行结束的提醒到指定邮箱。
想实现Python文件的后台运行,命令为:
nohup python -u myscript.py params1 > nohup.out 2>&1 &
其中参数 -u 为使得python不启用缓冲,可以及时将输出信息输出到 nohup.out 文件中。
python脚本程序自动后台运行后,该脚本调用的程序也会在后台运行,关闭当前终端不会kill程序。
1 import time
2 import os
3 import subprocess
4 import smtplib
5 from email.mime.text import MIMEText
6
7
8 def doSth():
9 k=0
10 while k < 30:
11 time.sleep(5)
12 k=k+1
13 print('wake up')
14
15 def sendEmail(filename):
16 _user="13956047103@163.com"
17 _pwd="zxcvbnp"
18 _to="lhailong@mail.ustc.edu.com"
19 text="program in "+filename+"is finished!"
20 msg=MIMEText(text)
21 msg["Subject"]="program run result"
22 msg["From"]=_user
23 msg["To"]=_to
24
25 s=smtplib.SMTP("smtp.163.com",timeout=25)
26 s.login(_user, _pwd)
27 s.sendmail(_user, _to, msg.as_string())
28 s.close()
29
30
31 k=0
32 cwd=os.getcwd()
33 for(folderName, subfolders, filenames) in os.walk('.'):
34 print(k)
35 k=k+1
36 print('******************************************')
37 print('current folder name: '+ folderName)
38 if subfolders:
39 print('subfolder:')
40 print(subfolders)
41 if filenames:
42 print('sub file:')
43 print(filenames)
44
45 runfile='./r_test.out'
46 os.chdir(folderName)
47 try:
48 # os.system(folderName+'/make')
49 myMake=subprocess.Popen('make')
50 myMake.wait()
51 runExe=subprocess.Popen(runfile)
52 runExe.wait()
53 # os.system(runfile)
54 sendEmail(folderName)
55 doSth()
56 except:
57 print('no exe in this file')
58 print('******************************************')
59 print('')
60 os.chdir(cwd)