#-*-coding:GBK -*-
import pynvml
pynvml.nvmlInit()
import time
import os
#from send_email import send_msg
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def send_msg(target_email,msg):
sender = 'xxxxx@163.com'
receivers = [target_email] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
# 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
message = MIMEText(msg, 'plain', 'utf-8')
subject = 'nvidia显卡监控'
message['Subject'] = Header(subject, 'utf-8')
#server = smtplib.SMTP('smtp.163.com', 587)
server = smtplib.SMTP_SSL('smtp.163.com')
server.connect('smtp.163.com',465)
#server.starttls()
#server.ehlo()
server.login(sender, "xxxxxxx")
server.sendmail(sender, receivers, message.as_string())
server.quit()
#smtpObj = smtplib.SMTP("localhost",1025)
#try:
# smtpObj.sendmail(sender, receivers, message.as_string())
# print("邮件发送成功")
#except smtplib.SMTPException:
# print("Error: 无法发送邮件")
def watch_nvidia(nvidia_ids,min_memory):
flag = [1 for i in nvidia_ids]
for i in nvidia_ids:
handle = pynvml.nvmlDeviceGetHandleByIndex(i)
meminfo = pynvml.nvmlDeviceGetMemoryInfo(handle)
print("card {} free memory is {}GB".format(i,meminfo.free * 1.0 /(1024**3)))
if meminfo.free * 1.0 /(1024**3) > min_memory:
flag[i-1]=0
else:
flag[i-1]=1
if 0 in flag:
free_num = 0
for i in flag:
if i == 0:
free_num += 1
return free_num
else:
print("no free card!")
return -1
nvidia_ids = [0,1] # 显卡id
min_memory = 8 # 最小可用显存 GB
while True:
flag = watch_nvidia(nvidia_ids,min_memory)
if flag >= 1:
send_msg("xxxxxxx@bjtu.edu.cn","{}张显卡空闲".format(flag))
#os.system("sh veri.sh") # your command
break
time.sleep(10)