欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python 監(jiān)控某個(gè)進(jìn)程內(nèi)存的情況問題

 更新時(shí)間:2022年05月16日 11:34:52   作者:一直在測(cè)試路上前進(jìn)  
這篇文章主要介紹了python 監(jiān)控某個(gè)進(jìn)程內(nèi)存的情況問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

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

測(cè)試場(chǎng)景:

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

手段:

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

方法:

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

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

分析了具體思路

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

2.如果不存在,就重啟;不存在就不進(jìn)行后續(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請(qǐng)求
        # url = "http://159.138.131.148/server_offline.html"
        # request = urllib.request(url)
        global count
        count += 1
        print(formattime + '第' + str(count) + '次檢測(cè)發(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) + '次檢測(cè)正在運(yùn)行中')
    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的運(yùn)行狀態(tài),如果CPU一直維持在80%以上 就主動(dòng)殺死進(jìn)程,并重啟進(jìn)程,使用了牛逼的psutil 跨系統(tǒng)平臺(tái)操作庫。實(shí)現(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)測(cè)穩(wěn)定在5%以內(nèi) 殺死進(jìn)程并重啟
        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)測(cè)cpu,cpu占用率:%s' % num)
    global timer
    timer = Timer(30, look_cpu, ("start C:\Progra~1\CloudControlServer\CloudControlServer.exe",))
    timer.start()

但是第三天老板有了新的需求,需要做個(gè)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')]
    # 提供重啟進(jìn)程api
    elif path == '/restart_process':
        # os.system('shutdowm.exe -r')
        res = remote_restart_process("start C:\Progra~1\CloudControlServer\CloudControlServer.exe")
        return [b'success']
# 啟動(dòng)web服務(wù)器提供api .port=8060
httpserver = make_server('', 8060, application)
httpserver.serve_forever()
'''
三個(gè)api接口:
ip:8060/cpu     cpu信息
ip:8060/state   cpu+memory狀態(tài)
ip:8060/restart_process    重啟進(jìn)程
'''

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python之ReportLab繪制條形碼和二維碼的實(shí)例

    Python之ReportLab繪制條形碼和二維碼的實(shí)例

    下面小編就為大家分享一篇Python之ReportLab繪制條形碼和二維碼的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-01-01
  • python?PyVCF文件處理VCF文件格式實(shí)例詳解

    python?PyVCF文件處理VCF文件格式實(shí)例詳解

    這篇文章主要為大家介紹了python?PyVCF文件處理VCF文件格式實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-07-07
  • Python變量作用范圍實(shí)例分析

    Python變量作用范圍實(shí)例分析

    這篇文章主要介紹了Python變量作用范圍,實(shí)例分析了Python中變量的定義與相關(guān)作用域,是Python學(xué)習(xí)中非常重要的基本技巧,需要的朋友可以參考下
    2015-07-07
  • python 算法 排序?qū)崿F(xiàn)快速排序

    python 算法 排序?qū)崿F(xiàn)快速排序

    主要分為兩個(gè)子算法,PARTITION(A, p, r)以A[r]為基準(zhǔn)對(duì)數(shù)組進(jìn)行一個(gè)劃分,比A[r]小的放在左邊,比A[r]大的放在右邊
    2012-06-06
  • rabbitmq(中間消息代理)在python中的使用詳解

    rabbitmq(中間消息代理)在python中的使用詳解

    這篇文章主要介紹了rabbitmq(中間消息代理)在python中的使用詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-12-12
  • python實(shí)用代碼片段收集貼

    python實(shí)用代碼片段收集貼

    這篇文章主要介紹了python實(shí)用代碼片段收集貼,本文收集了如獲取一個(gè)類的所有子類、計(jì)算運(yùn)行時(shí)間、SQLAlchemy簡單使用、實(shí)現(xiàn)類似Java或C中的枚舉等實(shí)用功能代碼,需要的朋友可以參考下
    2015-06-06
  • Python中requests、aiohttp、httpx性能比拼

    Python中requests、aiohttp、httpx性能比拼

    本文主要介紹了Python中requests、aiohttp、httpx性能比拼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • python檢查序列seq是否含有aset中項(xiàng)的方法

    python檢查序列seq是否含有aset中項(xiàng)的方法

    這篇文章主要介紹了python檢查序列seq是否含有aset中項(xiàng)的方法,涉及Python針對(duì)序列的相關(guān)判斷技巧,需要的朋友可以參考下
    2015-06-06
  • Python基于callable函數(shù)檢測(cè)對(duì)象是否可被調(diào)用

    Python基于callable函數(shù)檢測(cè)對(duì)象是否可被調(diào)用

    這篇文章主要介紹了Python基于callable函數(shù)檢測(cè)對(duì)象是否可被調(diào)用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-10-10
  • 如何用Python實(shí)現(xiàn)簡單的Markdown轉(zhuǎn)換器

    如何用Python實(shí)現(xiàn)簡單的Markdown轉(zhuǎn)換器

    這篇文章主要介紹了如何用Python實(shí)現(xiàn)簡單的Markdown轉(zhuǎn)換器,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-07-07

最新評(píng)論