Last active
November 8, 2019 02:16
-
-
Save huang4207100/23100f2492d5fdafa636b4bedcc875cf to your computer and use it in GitHub Desktop.
[python监控] python监控进程的CPU和内存 #python #psutil
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| import time | |
| import psutil | |
| # get pid from args | |
| if len(sys.argv) < 2: | |
| print ("missing pid arg") | |
| sys.exit() | |
| # get process | |
| pid = int(sys.argv[1]) | |
| p = psutil.Process(pid) | |
| # monitor process and write data to file | |
| interval = 3 # polling seconds | |
| with open("process_monitor_" + p.name() + '_' + str(pid) + ".csv", "a+") as f: | |
| f.write("time,cpu%,mem%\n") # titles | |
| while True: | |
| current_time = time.strftime('%Y%m%d-%H%M%S',time.localtime(time.time())) | |
| cpu_percent = p.cpu_percent() | |
| mem_percent = p.memory_percent() | |
| line = current_time + ',' + str(cpu_percent) + ',' + str(mem_percent) | |
| print (line) | |
| f.write(line + "\n") | |
| time.sleep(interval) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment