How to get current CPU and RAM usage in Python?

前端 未结 16 1787
攒了一身酷
攒了一身酷 2020-11-22 04:09

What\'s your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for *nix and Windows platforms.

There s

16条回答
  •  不要未来只要你来
    2020-11-22 05:11

    Taken feedback from first response and done small changes

                #!/usr/bin/env python
                #Execute commond on windows machine to install psutil>>>>python -m pip install psutil
                import psutil
    
                print ('                                                                   ')
                print ('----------------------CPU Information summary----------------------')
                print ('                                                                   ')
    
                # gives a single float value
                vcc=psutil.cpu_count()
                print ('Total number of CPUs :',vcc)
    
                vcpu=psutil.cpu_percent()
                print ('Total CPUs utilized percentage :',vcpu,'%')
    
                print ('                                                                   ')
                print ('----------------------RAM Information summary----------------------')
                print ('                                                                   ')
                # you can convert that object to a dictionary 
                #print(dict(psutil.virtual_memory()._asdict()))
                # gives an object with many fields
                vvm=psutil.virtual_memory()
    
                x=dict(psutil.virtual_memory()._asdict())
    
                def forloop():
                    for i in x:
                        print (i,"--",x[i]/1024/1024/1024)#Output will be printed in GBs
    
                forloop()
                print ('                                                                   ')
                print ('----------------------RAM Utilization summary----------------------')
                print ('                                                                   ')
                # you can have the percentage of used RAM
                print('Percentage of used RAM :',psutil.virtual_memory().percent,'%')
                #79.2
                # you can calculate percentage of available memory
                print('Percentage of available RAM :',psutil.virtual_memory().available * 100 / psutil.virtual_memory().total,'%')
                #20.8
    

提交回复
热议问题