psutil learning notes

Keywords: Python network Google lsof Linux

  1. psutil introduction
    psutil is a cross platform library( )It can easily obtain the process and system utilization (including CPU, memory, disk, network, etc.) information of the system. It is mainly used in system monitoring, analysis and limitation of system resources and process management. It implements the functions provided by equivalent command-line tools, such as ps, top, lsof, netstat, ifconfig, who, df, kill, free, nice, ionice, iostat, iotop, uptime, pidof, tty, taskset, pmap, etc. Currently, it supports 32-bit and 64 bit Linux, Windows, OS X, FreeBSD, Sun Solaris and other operating systems,
  2. install

    pip install psutil
  3. Use
  • cpu Information

    # Display all logic information of cpu
    b = psutil.cpu_times()
    # View the cpu time ratio of users
    c = psutil.cpu_times().user
    # View the physical number of CPUs
    d = psutil.cpu_count(logical=False)
    print(b, c, d)
  • Disk information

    # Get disk full information
    # Get the usage of partition (parameter)
  • Memory information

    # All information of system memory
    a = psutil.virtual_memory()
    # Total system memory
    # The system has used memory
    # System free memory
    # Get swap memory information
  • Disk information

    # Get disk full information
    # Get the usage of partition (parameter)
  • network information

    # Get the total IO information of the network
    # Obtain IO information of each network interface
  • Other system information

    # Current user information
    # Get boot
    import datetime
    print(datetime.datetime.utcfromtimestamp(psutil.boot_time()).strftime('%Y-%m-%d %H:%M:%S'))
  • Process information

    pids = psutil.pids() #List all process IDs
    pids_4644= psutil.Process(4644) #List the process information with the specified pid of 4644
    print (pids)
    print (    #Output process name
    print (pids_4644.exe())     #Output process path
    print (pids_4644.cwd())     #Output absolute path
    print (pids_4644.status())  #Output process status
    print (pids_4644.create_time()) #Output creation time and timestamp format
    #print (pids_4644.gid())        #Output process gid information
    print (pids_4644.cpu_times)     #Output cpu time information, including user and system cpu time
    print (pids_4644.cpu_affinity()) #get process cpu affinity
    print (pids_4644.memory_percent()) #Process utilization
    print (pids_4644.memory_info)    #Process memory information
    print (pids_4644.io_counters())  #Process IO information, including read / write IO number and byte number
    print (pids_4644.connections())      #Returns the namedutples list of the open process socket, including fs,family, etc
    print (pids_4644.num_threads())     #Number of threads opened by process

Posted by interrupt on Wed, 04 Dec 2019 11:32:29 -0800