溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python如何監(jiān)控某個進程內(nèi)存的情況

發(fā)布時間:2022-05-16 14:23:45 來源:億速云 閱讀:368 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要講解了“python如何監(jiān)控某個進程內(nèi)存的情況”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“python如何監(jiān)控某個進程內(nèi)存的情況”吧!

python監(jiān)控某個進程內(nèi)存

測試場景:

  • 某個客戶端程序長時間運行后存在內(nèi)存泄漏問題,現(xiàn)在開發(fā)解決了需要去驗證這個問題是否還存在,并要求出具相應(yīng)測試驗證報告。

手段:

  • 需要有一個工具能夠?qū)崟r去獲取該程序進程一直運行下占用內(nèi)存,CPU使用率情況。

方法:

  • python去實現(xiàn)這么個監(jiān)控功能 

import sys
import time
import psutil
sys.argv
# get pid from args
#獲取命令行輸入的參數(shù)個數(shù),sys.ary是一個列表
#如果列表參數(shù)<2,說明只輸入了python 文件名稱.py,則退出不繼續(xù)運行
if len(sys.argv) < 2:
	print ("沒有輸入要監(jiān)控的進程編號")
	sys.exit()
 
#獲取進程
print("打印進程號:"+sys.argv[1])
pid = int(sys.argv[1])
p = psutil.Process(pid)
#監(jiān)控進程并將獲取CPU,內(nèi)存使用情況寫入csv文件中
interval = 60 # 獲取CPU,內(nèi)存使用情況輪詢時間間隔
num=100
with open("process_monitor_" + p.name() + '_' + str(pid) + ".csv", "a+") as f:
	f.write("時間,cpu使用率(%),內(nèi)存使用率(%),內(nèi)存使用值MB\n") # csv文件表頭列名:time,cpu使用率,內(nèi)存使用率,內(nèi)存占用值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('當(dāng)前進程的內(nèi)存使用:',mem_info)
		print('當(dāng)前進程的內(nèi)存使用:%.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如何監(jiān)控某個進程內(nèi)存的情況

python監(jiān)控進程并重啟

最近公司的游戲服務(wù)器經(jīng)常掉線,老板只能讓員工不定時登陸服務(wù)器看死掉沒有,都快成機器人了,因此python自動化監(jiān)測進程運用腳本就產(chǎn)生了。

分析了具體思路

1.做個線程定時器,每隔20s執(zhí)行系統(tǒng)命令查詢指定進程名稱是否存在

2.如果不存在,就重啟;不存在就不進行后續(xù)的操作。

相關(guān)代碼很簡單

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)
        # 發(fā)送HTTP請求
        # url = "http://159.138.131.148/server_offline.html"
        # request = urllib.request(url)
        global count
        count += 1
        print(formattime + '第' + str(count) + '次檢測發(fā)現(xiàn)異常重連')
        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()

搞定?。。?/p>

接下來有了新的需求~~  需要監(jiān)控CPU的運行狀態(tài),如果CPU一直維持在80%以上 就主動殺死進程,并重啟進程,使用了牛逼的psutil 跨系統(tǒng)平臺操作庫。實現(xiàn)代碼如下:

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負(fù)載超過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]
        # 判斷兩次監(jiān)測穩(wěn)定在5%以內(nèi) 殺死進程并重啟
        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('正在監(jiān)測cpu,cpu占用率:%s' % num)
    global timer
    timer = Timer(30, look_cpu, ("start C:\Progra~1\CloudControlServer\CloudControlServer.exe",))
    timer.start()

但是第三天老板有了新的需求,需要做個web端 將CPU和內(nèi)存信息開放api 并且支持遠(yuǎn)程重啟,我的思路是利用python自帶的http服務(wù)類庫,省去了socket編程的麻煩,直接輸入IP port  即可,這里使用了wsgiref.simple_server

# web服務(wù)應(yīng)用函數(shù)
def application(environ, start_response):
    path = environ.get('PATH_INFO')
    start_response('200 OK', [])
    # 提供cpu 狀態(tài)信息
    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服務(wù)器提供api .port=8060
httpserver = make_server('', 8060, application)
httpserver.serve_forever()
'''
三個api接口:
ip:8060/cpu     cpu信息
ip:8060/state   cpu+memory狀態(tài)
ip:8060/restart_process    重啟進程
'''

感謝各位的閱讀,以上就是“python如何監(jiān)控某個進程內(nèi)存的情況”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對python如何監(jiān)控某個進程內(nèi)存的情況這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI