训练网络经常半夜才训练完,有时为了不浪费时间,晚上特意调了闹钟起来改代码、继续训练等。大半夜设闹钟起来跑代码太难受了,所以这次写了这两个代码,以后少受点罪。
1、定时执行脚本
代码:
import os
import time
set_time = '00:00:00' # 此处设置每天定时的时间
cmd = ''
print("——————————waiting to execute task——————————")
while True:
time_now = time.strftime("%H:%M:%S", time.localtime()) # 刷新
if time_now == set_time:
time.sleep(2) # 因为以秒定时,所以暂停2秒,使之不会在1秒内执行多次
subject = time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime()) + " running command"
print(subject)
## 执行命令
os.system(cmd)
break # 执行完毕退出循环
流程:
- 设置脚本运行时间(如:
set_time = '00:00:00'
) - 设置执行脚本命令(如:
cmd = 'python 123.py'
),可自行添加多条命令
输出:
2、进程结束执行脚本
代码:
import os
import time
import psutil
"""
windows查询python.exe进程的ProcessId:
wmic process where name="python.exe" list full
"""
ProcessId = 63112
cmd = ''
pid = psutil.Process(ProcessId)
while True:
time.sleep(5) # 每隔n秒查询一次进程运行情况
if pid.is_running():
p = psutil.Process(ProcessId)
exec_time = time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime())
print(exec_time + 'pid-%s, pname-%s' % (ProcessId, p.name()))
else:
print('ProcessId is over, running command:')
os.system(cmd)
break
流程:
作者以python.exe为例
1、 WIN+R
进入cmd
界面,输入命令:wmic process where name="python.exe" list full
,获取如下信息:
其中主要确定所执行的py文件和对应的进程号。Linux 和 Windows 查看当前运行的 python 进程及 GPU、CPU、磁盘利用率
2、 设置进程ID(如:ProcessId = 63112
)
3、 设置执行脚本命令(如:cmd = 'python 123.py'
),可自行添加多条命令
运行结果:
3、添加GPU空闲内存条件
主要是读取GPU剩余显存的大小,再添加到上面的代码中作为命令执行的条件。
首先是模块安装:
pip install nvidia-ml-py3
如果是python2,则 pip install nvidia-ml-py2
读取显卡剩余显存大小
import pynvml
pynvml.nvmlInit()
# GPU 0 的使用情况
handle_0 = pynvml.nvmlDeviceGetHandleByIndex(0)
meminfo_0 = pynvml.nvmlDeviceGetMemoryInfo(handle_0)
Totol_GPU0 = meminfo_0.total / (1024 ** 3)
Used_GPU0 = meminfo_0.used / (1024 ** 3)
Free_GPU0 = meminfo_0.free / (1024 ** 3)
print('Totol_GPU0 = ' + str(Totol_GPU0) + 'G') # 显卡总的显存大小
print('Used_GPU0 = ' + str(Used_GPU0) + 'G') # 显卡已使用显存大小
print('Free_GPU0 = ' + str(Free_GPU0) + 'G') # 显卡剩余显存大小
# GPU 1 的使用情况
# handle_1 = pynvml.nvmlDeviceGetHandleByIndex(1)
# meminfo_1 = pynvml.nvmlDeviceGetMemoryInfo(handle)
# Totol_GPU1 = meminfo.total / (1024 ** 3)
# Used_GPU1 = meminfo.used / (1024 ** 3)
# Free_GPU1 = meminfo.free / (1024 ** 3)
# print('Totol_GPU1 = ' + str(Totol_GPU0) + 'G') # 显卡总的显存大小
# print('Used_GPU1 = ' + str(Used_GPU0) + 'G') # 显卡已使用显存大小
# print('Free_GPU1 = ' + str(Free_GPU0) + 'G') # 显卡剩余显存大小