網站首頁 編程語言 正文
python監控某個進程內存
測試場景:
- 某個客戶端程序長時間運行后存在內存泄漏問題,現在開發解決了需要去驗證這個問題是否還存在,并要求出具相應測試驗證報告。
手段:
- 需要有一個工具能夠實時去獲取該程序進程一直運行下占用內存,CPU使用率情況。
方法:
- python去實現這么個監控功能?
import sys
import time
import psutil
sys.argv
# get pid from args
#獲取命令行輸入的參數個數,sys.ary是一個列表
#如果列表參數<2,說明只輸入了python 文件名稱.py,則退出不繼續運行
if len(sys.argv) < 2:
print ("沒有輸入要監控的進程編號")
sys.exit()
#獲取進程
print("打印進程號:"+sys.argv[1])
pid = int(sys.argv[1])
p = psutil.Process(pid)
#監控進程并將獲取CPU,內存使用情況寫入csv文件中
interval = 60 # 獲取CPU,內存使用情況輪詢時間間隔
num=100
with open("process_monitor_" + p.name() + '_' + str(pid) + ".csv", "a+") as f:
f.write("時間,cpu使用率(%),內存使用率(%),內存使用值MB\n") # csv文件表頭列名:time,cpu使用率,內存使用率,內存占用值MB
while num>0:
num=num-1
current_time = time.strftime('%Y%m%d-%H%M%S',time.localtime(time.time()))
cpu_percent = p.cpu_percent() # better set interval second to calculate like: p.cpu_percent(interval=0.5)
mem_percent = p.memory_percent()
mem_info=p.memory_info().rss
mem_MB=4096 / mem_percent
print('當前進程的內存使用:',mem_info)
print('當前進程的內存使用:%.4f MB' %mem_MB)
line = current_time + ',' + str(cpu_percent) + ',' + str(mem_percent)+','+str(mem_MB)
print (line)
f.write(line + "\n")
time.sleep(interval)
python監控進程并重啟
最近公司的游戲服務器經常掉線,老板只能讓員工不定時登陸服務器看死掉沒有,都快成機器人了,因此python自動化監測進程運用腳本就產生了。
分析了具體思路
1.做個線程定時器,每隔20s執行系統命令查詢指定進程名稱是否存在
2.如果不存在,就重啟;不存在就不進行后續的操作。
相關代碼很簡單
def restart_process(process_name):
red = subprocess.Popen('tasklist', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
tasklist_str = red.stdout.read().decode(encoding='gbk')
re_path = process_name.split("\\")[-1]
formattime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if re_path not in tasklist_str:
# obj = connect_emai()
# sendmail('程序卡掉正在重啟。。。', obj)
# 發送HTTP請求
# url = "http://159.138.131.148/server_offline.html"
# request = urllib.request(url)
global count
count += 1
print(formattime + '第' + str(count) + '次檢測發現異常重連')
cmd = process_name
os.system(process_name)
# res = subprocess.Popen(cmd,stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
# print(res.stderr.read().decode(encoding='gbk'),res.stdout.read().decode(encoding='gbk'))
# sendmail('重啟連接成功!',obj)
print('yes,connected')
else:
global error_count
error_count += 1
print(formattime + '第' + str(error_count) + '次檢測正在運行中')
global timer
timer = Timer(20, restart_process, ("start C:\Progra~1\CloudControlServer\CloudControlServer.exe",))
timer.start()
count = 0
error_count = 0
timer = Timer(20, restart_process, ("start C:\Progra~1\CloudControlServer\CloudControlServer.exe",))
timer.start()
搞定!!!
接下來有了新的需求~~ ?需要監控CPU的運行狀態,如果CPU一直維持在80%以上 就主動殺死進程,并重啟進程,使用了牛逼的psutil 跨系統平臺操作庫。實現代碼如下:
def look_cpu(process_name):
res = subprocess.Popen('wmic cpu get LoadPercentage', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
res_str = res.stdout.read().decode(encoding='gbk')
num = re.findall('\d+', res_str)[0]
if int(num) > 80:
print('cup負載超過10%')
time.sleep(10)
res_twice = subprocess.Popen('wmic cpu get LoadPercentage', stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True)
res_twice_str = res_twice.stdout.read().decode(encoding='gbk')
num_twice = re.findall('\d+', res_twice_str)[0]
# 判斷兩次監測穩定在5%以內 殺死進程并重啟
if abs(int(num) - int(num_twice)) < 5:
tasklist = subprocess.Popen('tasklist | findstr CloudControlServer.exe', stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True)
res = tasklist.stdout.read().decode(encoding='gbk')
pid = re.search('\d{1,4}', res).group()
cmd = 'taskkill -f /pid %s' % pid
time.sleep(0.5)
print(cmd)
os.system('taskkill -f /pid %s' % pid)
os.system(process_name)
print('正在監測cpu,cpu占用率:%s' % num)
global timer
timer = Timer(30, look_cpu, ("start C:\Progra~1\CloudControlServer\CloudControlServer.exe",))
timer.start()
但是第三天老板有了新的需求,需要做個web端 將CPU和內存信息開放api 并且支持遠程重啟,我的思路是利用python自帶的http服務類庫,省去了socket編程的麻煩,直接輸入IP port ?即可,這里使用了wsgiref.simple_server
# web服務應用函數
def application(environ, start_response):
path = environ.get('PATH_INFO')
start_response('200 OK', [])
# 提供cpu 狀態信息
if path == '/cpu':
res = subprocess.Popen('wmic cpu get LoadPercentage', stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True)
res_str = res.stdout.read().decode(encoding='gbk')
resp = {'cpu': re.findall('\d+', res_str)[0]}
return [json.dumps(resp).encode(encoding='utf-8')]
# 提供cpu + memory 信息
elif path == '/state':
cpu = psutil.cpu_percent()
memory = psutil.virtual_memory()
memory_lv = float(memory.used) / float(memory.total) * 100
res = {'cpu': cpu, 'memory': memory_lv}
return [json.dumps(res).encode(encoding='utf-8')]
# 提供重啟進程api
elif path == '/restart_process':
# os.system('shutdowm.exe -r')
res = remote_restart_process("start C:\Progra~1\CloudControlServer\CloudControlServer.exe")
return [b'success']
# 啟動web服務器提供api .port=8060
httpserver = make_server('', 8060, application)
httpserver.serve_forever()
'''
三個api接口:
ip:8060/cpu cpu信息
ip:8060/state cpu+memory狀態
ip:8060/restart_process 重啟進程
'''
原文鏈接:https://blog.csdn.net/weixin_43533308/article/details/123929124
相關推薦
- 2022-07-31 pandas中提取DataFrame某些列的一些方法_python
- 2022-04-01 maven的settings.xml文件中配置多個nexus倉庫
- 2022-09-05 C語言之sizeof與strlen的使用及區別_C 語言
- 2022-07-06 C語言舉例講解i++與++i之間的區別_C 語言
- 2023-01-11 解讀時間序列分析之ADF檢驗_python
- 2022-04-21 catalina.out 和 catalina.log 的區別和用途
- 2023-01-31 golang獲取變量或對象類型的幾種方式總結_Golang
- 2022-05-12 uni-app混合原生安卓開發
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支