Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does python monitor the memory of a process

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how python monitors the memory of a process". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how python monitors the memory of a process".

Python monitors a process memory

Test scenario:

A client program has a memory leak problem after running for a long time, but now the developer has solved the need to verify whether the problem still exists, and requires a corresponding test verification report.

Means:

There needs to be a tool that can get the memory consumption and CPU usage of the program process in real time.

Methods:

Python to implement such a monitoring function

Import sysimport timeimport psutilsys.argv# get pid from args# gets the number of parameters entered on the command line. Sys.ary is a list # if the list parameter 0: num=num-1 current_time = time.strftime ('% Y% m% dmi% 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 ('memory usage of current process:' Mem_info) print ('current process memory usage:% .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 monitors the process and restarts

Recently, the company's game server is often offline, and the boss can only let employees log in to the server from time to time to see if they are dead or not. it is almost a robot, so the script for python automatic monitoring process is generated.

The specific ideas are analyzed.

1. Make a thread timer and execute system commands every 20 seconds to query whether the specified process name exists.

two。 If it does not exist, restart it; if it does not exist, no subsequent operations will be performed.

The related code is very simple 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% HV% MV% S') if re_path not in tasklist_str: # obj = connect_emai () # sendmail ('the program is being restarted.' , obj) # send HTTP request # url = "http://159.138.131.148/server_offline.html" # request = urllib.request (url) global count count + = 1 print (formattime +'th'+ str (count) + 'abnormal reconnection found') 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 ('restart connection successfully!' , obj) print ('yes,connected') else: global error_count error_count + = 1 print (formattime +' th'+ str (error_count) + 'second test is running') global timer timer = Timer (20, restart_process, ("start C:\ Progra~1\ CloudControlServer\ CloudControlServer.exe",) timer.start () count = 0error_count = 0timer = Timer (20, restart_process ("start C:\ Progra~1\ CloudControlServer\ CloudControlServer.exe",) timer.start ()

Got it!

Next, there is a new requirement ~ ~ you need to monitor the running status of CPU. If the CPU remains above 80%, you will actively kill the process and restart the process, using the powerful psutil cross-system platform operation library. The implementation code is as follows:

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 ('\ dweeds, res_str) [0] if int (num) > 80: print ('cup load exceeds 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 ('\ dcats' Res_twice_str) [0] # determine that twice monitoring is stable within 5% to kill the process and restart 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 {1pm 4}' Res) .group () cmd = 'taskkill-f / pid% s'% pid time.sleep (cmd) os.system ('taskkill-f / pid% s'% pid) os.system (process_name) print ('monitoring cpu Cpu occupancy:% s'% num) global timer timer = Timer (30, look_cpu, ("start C:\ Progra~1\ CloudControlServer\ CloudControlServer.exe",)) timer.start ()

But on the third day, the boss had a new requirement. He needed to do a web side to open CPU and memory information to api and support remote restart. My idea is to use the http service class library that comes with python to save the trouble of socket programming. Just enter IP port directly. Wsgiref.simple_server is used here.

# web service application function def application (environ, start_response): path = environ.get ('PATH_INFO') start_response (' 200 OK', []) # provide cpu status information 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 ('\ daddy') Res_str) [0]} return [json.dumps (resp) .encode (encoding='utf-8')] # provide cpu + memory information 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')] # provides the restart process api elif path = = / restart_process': # os.system (' shutdowm.exe-r') res = remote_restart_process ("start C:\ Progra~1\ CloudControlServer\ CloudControlServer.exe") return [baked codes'] # starts the web server and provides api .port = 8060httpserver = make_server ('', 8060) Application) httpserver.serve_forever ()''three api interfaces: ip:8060/cpu cpu message ip:8060/state cpu+memory status ip:8060/restart_process restart process' 'Thank you for reading The above is the content of "how python monitors the memory of a process". After the study of this article, I believe you have a deeper understanding of how python monitors the memory of a process, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report