Information systems acquisition module psutil

psutil module Introduction

  psutil cut is an open source cross-platform library that provides convenient function is used to get before doing system information such as CPU, memory, disk, network, and so on. In addition, psutil can also be used for process management, including the process of determining whether there is, get the list of processes, and other processes for details. And psutil also provides many of the features command line tools, including: ps, top, lsof, netstat, ifconfig, who, df, kill, free, nice, ionice, iostat, iotop, uptime, pidof, tty, taskset, pmap .

  psutil is a cross-platform library, which supports the following operating systems found on the official website.

- Linux
- Windows
- OSX
- FreeBSD
- OpenBSD
- NetBSD
- Sun Solaris
- AIX

Works with Python versions from 2.6 to 3.X.

Installation psutil module

  psutil is a third party open source project, it is necessary to install in order to use. Here use pip install command

`pip3 ``install` `psutil`

 psutil comprising abnormality classes, functions and constants function, wherein the function of the system function to retrieve the information, such as CPU, disk, memory, network. Class used to implement process management functions.

Function Function

  The performance function, here is divided into the following categories, the following will be described the several dimensions of performance function psutil provided.

CPU-related

  cpu_count (, [logical]): Returns the number of logical CPU default, when the logical parameters set to False, returns the number of physical CPU.

`>>> ``import` `psutil``>>> psutil.cpu_count()``8``>>> psutil.cpu_count(logical``=``False``)``4`

  cpu_percent (, [percpu], [interval]): Returns the CPU utilization, percpu show all the physical core utilization, 0 interval, the display is not blocked when the average utilization during execution of time interval is set to True

`>>> ``import` `psutil``>>> psutil.cpu_percent()``6.7``>>> psutil.cpu_percent(percpu``=``True``)``[``17.7``, ``0.9``, ``11.0``, ``1.0``, ``11.1``, ``0.9``, ``10.7``, ``0.9``]``>>> psutil.cpu_percent(percpu``=``True``,interval``=``2``)``[``16.0``, ``0.0``, ``8.5``, ``1.0``, ``14.4``, ``0.5``, ``9.5``, ``1.0``]`

  cpu_time (, [percpu]): Returns the name of cpu time tuple (namedtuple) takes the form of, percpu retrieves each CPU time spent

`>>> ``import` `psutil``>>> psutil.cpu_times()``scputimes(user``=``5471.2``, nice``=``0.0``, system``=``5633.92``, idle``=``1295903.87``, iowait``=``2651.2``, irq``=``16.44``, softirq``=``137.87``, steal``=``0.0``, guest``=``0.0``)``>>> psutil.cpu_times(percpu``=``True``)``[scputimes(user``=``2803.53``, nice``=``0.0``, system``=``2824.3``, idle``=``648996.02``, iowait``=``153.71``, irq``=``16.26``, softirq``=``64.71``, steal``=``0.0``, guest``=``0.0``),``scputimes(user``=``2667.74``, nice``=``0.0``, system``=``2809.74``, idle``=``646935.11``, iowait``=``2497.58``, irq``=``0.18``, softirq``=``73.15``, steal``=``0.0``, guest``=``0.0``)]`

img Tuple easy way to get information about naming

  cpu_times_percent (, [percpu]): substantially the same function and cpu_times, watching can know the literal meaning, the function returns ratio is time consuming.

`>>> ``import` `psutil``>>> psutil.cpu_times_percent()``scputimes(user``=``0.3``, nice``=``0.0``, system``=``0.4``, idle``=``99.0``, iowait``=``0.3``, irq``=``0.0``, softirq``=``0.0``, steal``=``0.0``, guest``=``0.0``)``>>> psutil.cpu_times_percent(percpu``=``True``)``[scputimes(user``=``0.3``, nice``=``0.0``, system``=``0.4``, idle``=``99.3``, iowait``=``0.0``, irq``=``0.0``, softirq``=``0.0``, steal``=``0.0``, guest``=``0.0``),``scputimes(user``=``0.3``, nice``=``0.0``, system``=``0.4``, idle``=``98.7``, iowait``=``0.6``, irq``=``0.0``, softirq``=``0.0``, steal``=``0.0``, guest``=``0.0``)]`

  cpu_stats (): Returns the statistics of the CPU to name tuples of the form, including context switches, interrupts, software interrupts and system calls.

`>>> ``import` `psutil``>>> psutil.cpu_stats()``scpustats(ctx_switches``=``393538808``, interrupts``=``194683724``, soft_interrupts``=``151546977``, syscalls``=``0``)`

Memory-related

  virtual_memory (): returns the memory usage in the tuple named forms, including total memory, available memory, memory utilization, buffer cache, and the like. Bytes.

`>>> ``import` `psutil``>>> psutil.virtual_memory()``svmem(total``=``1964584960``, available``=``1375827968``, percent``=``30.0``, used``=``432644096``,``free``=``600588288``, active``=``710012928``, inactive``=``484106240``, buffers``=``238247936``,``cached``=``693104640``, shared``=``716800``)`

Press Ctrl + C to copy the code

Press Ctrl + C to copy the code

  swap_memory (): returns the tuple to name swap Memory usage form, comprising the swap pages swapped in and out.

`>>> ``import` `psutil``>>> psutil.swap_memory()``sswap(total``=``2113925120``, used``=``12206080``, free``=``2101719040``, percent``=``0.6``,``sin``=``29061120``, sout``=``87228416``)`

Disk-related

  disk_partitions ([all = False]): to name returns all tuples of the form mounted disk, comprising the disk name, the mount point of the file system type and other information. When all is equal to True, the mount comprising information return / proc file system and other special

`>>> ``import` `psutil``>>> psutil.disk_partitions()``[sdiskpart(device``=``'/dev/mapper/VolGroup-lv_root'``, mountpoint``=``'/'``, fstype``=``'ext4'``, opts``=``'rw'``),``sdiskpart(device``=``'/dev/sda1'``, mountpoint``=``'/boot'``, fstype``=``'ext4'``, opts``=``'rw'``),``sdiskpart(device``=``'/dev/mapper/VolGroup-lv_home'``, mountpoint``=``'/home'``, fstype``=``'ext4'``, opts``=``'rw'``)]` `# 查询指定挂载点的信息``>>> [ device ``for` `device ``in` `psutil.disk_partitions() ``if` `device.mountpoint ``=``=` `'/'` `]``[sdiskpart(device``=``'/dev/mapper/VolGroup-lv_root'``, mountpoint``=``'/'``, fstype``=``'ext4'``, opts``=``'rw'``)]`

  disk_usage (path): Returns the path where the disk usage to name tuple forms, including disk capacity, disk capacity has been used, disk space utilization.

`>>> ``import` `psutil``>>> psutil.disk_usage(``'/'``)``sdiskusage(total``=``32105152512``, used``=``11395198976``, free``=``19072290816``, percent``=``37.4``)`

  disk_io_counters ([perdisk]): Returns the disk io statistics (aggregated) to name tuples of the form, including read, write the number, read the number of bytes written and so on. When perdisk value is True, then list the statistics for a single disk (the dictionary: key for the disk name, value as a statistical namedtuple).

`import` `psutil``>>> psutil.disk_io_counters()``sdiskio(read_count``=``356568``, write_count``=``12058367``, read_bytes``=``12599494656``,``write_bytes``=``92961665024``, read_time``=``260945``, write_time``=``40815092``,``read_merged_count``=``32656``, write_merged_count``=``6334256``, busy_time``=``4421438``)``>>> psutil.disk_io_counters(perdisk``=``True``)``{``'sda1'``: sdiskio(read_count``=``737``, write_count``=``129``, read_bytes``=``7100416``,``write_bytes``=``5615616``, read_time``=``61``, write_time``=``578``, read_merged_count``=``496``,``write_merged_count``=``5349``, busy_time``=``257``), ``'sda2'``: sdiskio(read_count``=``161575``,``write_count``=``2825934``, read_bytes``=``6296442880``, write_bytes``=``46478901248``,``read_time``=``113557``, write_time``=``1580954``, read_merged_count``=``32160``,``write_merged_count``=``6328960``, busy_time``=``1026283``),``'dm-0'``: sdiskio(read_count``=``111371``, write_count``=``4944247``, read_bytes``=``2401461248``,``write_bytes``=``28988342272``, read_time``=``117846``, write_time``=``25992150``, read_merged_count``=``0``,``write_merged_count``=``0``, busy_time``=``2924323``), ``'dm-1'``: sdiskio(read_count``=``7482``,``write_count``=``21296``, read_bytes``=``30646272``, write_bytes``=``87228416``, read_time``=``8656``,``write_time``=``55930``, read_merged_count``=``0``, write_merged_count``=``0``, busy_time``=``1326``),``'dm-2'``: sdiskio(read_count``=``75407``, write_count``=``4267078``, read_bytes``=``3863860224``,``write_bytes``=``17403330560``, read_time``=``20849``, write_time``=``13185771``, read_merged_count``=``0``,``write_merged_count``=``0``, busy_time``=``469527``)}`

Network-related

  net_io_counter ([pernic]): Returns to name tuple network form system of each card io current statistics, including the number of bytes a transceiver, the number of send and receive packets, packet error situation and the situation deleted. When pernic True, the lists statistics for all network cards.

`>>> ``import` `psutil``>>> psutil.net_io_counters()``snetio(bytes_sent``=``428286398``, bytes_recv``=``542982044``, packets_sent``=``3768555``,``packets_recv``=``4169425``, errin``=``0``, errout``=``0``, dropin``=``0``, dropout``=``0``)``>>> psutil.net_io_counters(pernic``=``True``)``{``'lo'``: snetio(bytes_sent``=``339700487``, bytes_recv``=``339700487``, packets_sent``=``3363412``,``packets_recv``=``3363412``, errin``=``0``, errout``=``0``, dropin``=``0``, dropout``=``0``), ``'eth0'``:``snetio(bytes_sent``=``88616264``, bytes_recv``=``203314200``, packets_sent``=``405585``,``packets_recv``=``806516``, errin``=``0``, errout``=``0``, dropin``=``0``, dropout``=``0``), ``'virbr0'``: snetio(bytes_sent``=``0``,``bytes_recv``=``0``, packets_sent``=``0``, packets_recv``=``0``, errin``=``0``, errout``=``0``, dropin``=``0``, dropout``=``0``),``'virbr0-nic'``: snetio(bytes_sent``=``0``, bytes_recv``=``0``, packets_sent``=``0``, packets_recv``=``0``, errin``=``0``,``errout``=``0``, dropin``=``0``, dropout``=``0``)}`

  Details (namedtuple) returned as a list of each network connection: net_connections ([kind]). Named tuple contains fd, family, type, laddr, raddr, status, pid and other information. kind indicates the connection type of filter, the supported values ​​:( default inet)

  • inet:IPv4 and IPv6
    • inet4:IPv4
      • inet6: IPv6
        • tcp:TCP
          • tcp4:TCP over IPv4
            • tcp6:TCP over IPv6
              • udp:UDP
                • udp4:UDP over IPv4
                  • udp6:UDP over IPv6
                    • unix:UNIX socket (both UDP and TCP protocols)
                      • all:the sum of all the possible families and protocols
`>>> ``import` `psutil``>>> psutil.net_connections()``[sconn(fd``=``6``, family``=```2``>, ``type``=```1``>,``laddr``=``addr(ip``=``'0.0.0.0'``, port``=``8080``), raddr``=``(), status``=``'LISTEN'``, pid``=``21834``),``sconn(fd``=``3``, family``=```2``>, ``type``=```1``>,``laddr``=``addr(ip``=``'0.0.0.0'``, port``=``22``), raddr``=``(), status``=``'LISTEN'``, pid``=``8971``),``sconn(fd``=``-``1``, family``=```2``>, ``type``=```1``>,``laddr``=``addr(ip``=``'127.0.0.1'``, port``=``10050``), raddr``=``addr(ip``=``'127.0.0.1'``, port``=``46710``),``status``=``'TIME_WAIT'``, pid``=``None``),`

  net_if_addrs (): returns the configuration information of the network card in the form dictionary, and mac address comprises an IP address, subnet mask, and the broadcast address.

`>>> psutil.net_if_addrs()``{``'lo'``: [snic(family``=```2``>, address``=``'127.0.0.1'``, netmask``=``'255.0.0.0'``, broadcast``=``None``, ptp``=``None``),``snic(family``=```10``>, address``=``'::1'``, netmask``=``'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'``, broadcast``=``None``, ptp``=``None``),``snic(family``=```17``>, address``=``'00:00:00:00:00:00'``, netmask``=``None``, broadcast``=``None``, ptp``=``None``)],``'eth0'``: [snic(family``=```2``>, address``=``'10.0.0.3'``, netmask``=``'255.255.255.0'``, broadcast``=``'10.0.0.255'``, ptp``=``None``),``snic(family``=```10``>, address``=``'fe80::21c:42ff:fe52:ae47%eth0'``, netmask``=``'ffff:ffff:ffff:ffff::'``, broadcast``=``None``, ptp``=``None``),``snic(family``=```17``>, address``=``'00:1c:42:52:ae:47'``, netmask``=``None``, broadcast``=``'ff:ff:ff:ff:ff:ff'``, ptp``=``None``)],``'virbr0'``: [snic(family``=```2``>, address``=``'192.168.122.1'``, netmask``=``'255.255.255.0'``, broadcast``=``'192.168.122.255'``, ptp``=``None``),``snic(family``=```17``>, address``=``'52:54:00:04:87:ce'``, netmask``=``None``, broadcast``=``'ff:ff:ff:ff:ff:ff'``, ptp``=``None``)],``'virbr0-nic'``: [snic(family``=```17``>, address``=``'52:54:00:04:87:ce'``, netmask``=``None``, broadcast``=``'ff:ff:ff:ff:ff:ff'``, ptp``=``None``)]}`

  net_if_stats (): returns the card details, including whether to start, a communication type, transmission speed and MTU.

`>>> ``import` `psutil``>>> psutil.net_if_stats()``{``'lo'``: snicstats(isup``=``True``, duplex``=```0``>, speed``=``0``, mtu``=``65536``),``'eth0'``: snicstats(isup``=``True``, duplex``=```0``>, speed``=``0``, mtu``=``1500``),``'virbr0'``: snicstats(isup``=``True``, duplex``=```0``>, speed``=``0``, mtu``=``1500``),``'virbr0-nic'``: snicstats(isup``=``False``, duplex``=```2``>, speed``=``10``, mtu``=``1500``)}``>>>`

Other

  users (): name tuple as to return the information of the current login user, including user name, time of login, the terminal, and host information

`>>> ``import` `psutil``>>> psutil.users()``[suser(name``=``'root'``, terminal``=``'tty1'``, host``=``'', started``=``1513498496.0``, pid``=``9327``),``suser(name``=``'root'``, terminal``=``'pts/0'``, host``=``'10.0.0.2'``, started``=``1515335808.0``, pid``=``30838``),``suser(name``=``'root'``, terminal``=``'pts/2'``, host``=``'10.0.0.2'``, started``=``1515324032.0``, pid``=``21939``)]` `# start 表示登陆的时间(时间戳格式)`

  boot_time (): returns the system startup time stamp in the form of

`>>> ``import` `psutil``>>> psutil.boot_time()``1514678349.0`` `

img

1 >>> import datetime
2 >>> import psutil
3 >>> datetime.datetime.fromtimestamp(psutil.boot_time ()).strftime("%Y-%m-%d %H: %M: %S")

psutil process management

psutil also provides the ability to function as process management, including access to the list of processes, determine whether there is.

  Process categories: process of encapsulation, a method class may be used for more information, or send a signal to the process.

`>>> ``import` `psutil``>>> init_process ``=` `psutil.Process(``1``)``>>> init_process``psutil.Process(pid``=``1``, name``=``'launchd'``, started``=``'20:41:22'``)  ``# 进程id、名称、启动时间`

Process class provides many other methods used to obtain information related to the process

  • name: get the process name
  • cmdline: get to start the process of command line parameters
  • create_time: get the process creation time (timestamp format)
  • num_fds: the number of files opened by processes
  • The number of process sub-processes: num_threads
  • is_running: to determine whether the process is running
  • send_signal: sending a signal to the process, and other similar os.kill
  • kill: Send SIGKILL signal the end of the process
  • terminate: Send SIGTEAM signal the end of the process
`>>> ``import` `psutil``>>> process ``=` `psutil.Process(``3297``)``>>> process.name()``'Google Chrome Helper'``>>> process.create_time()``1519832141.532822``>>> process.num_fds()``22``>>> process.num_threads()``19`

  pids: returns the currently running processes in the form of a list of

  * Pid_exists: to determine whether a given point of presence pid *

  ** * * process_iter: iterative processes that are currently running, the return of each process Process object ******

`>>> psutil.pids()``[``3373``, ``3372``, ``3365``, ``3364``, ``3363``, ``3361``, ``3360``, ``3358``, ``3355``, ``3351``, ``3335``, ``3301``, ``3299``, ``3297``, ``3291``, ``3290``, ``3289``, ``3279``, ``3278``, ``3274``, ``3251``, ``3248``, ``3247``, ``3246``, ``3244``, ``3242``, ``3241``, ``3225``, ``3209``, ``3198``, ``3194``, ``3193``, ``3101``, ``2828``, ``2816``, ``2805``, ``2802``, ``2799``, ``2797``, ``2767``, ``2497``, ``2441``, ``2437``, ``2343``, ``2333``, ``2330``, ``2287``, ``2283``, ``2258``, ``2257``, ``2251``, ``2248``, ``2247``, ``2246``, ``2245``, ``2241``, ``2240``, ``2238``, ``2231``, ``2225``]``>>> psutil.pid_exists(``12``)``False``>>> ``list``(psutil.process_iter())[:``5``]``[psutil.Process(pid``=``0``, name``=``'kernel_task'``, started``=``'20:41:22'``), psutil.Process(pid``=``1``, name``=``'launchd'``, started``=``'20:41:22'``), psutil.Process(pid``=``48``, name``=``'UserEventAgent'``, started``=``'20:41:27'``), psutil.Process(pid``=``50``, name``=``'uninstalld'``, started``=``'20:41:27'``), psutil.Process(pid``=``51``, name``=``'kextd'``, started``=``'20:41:27'``)]  ``# 每个都是一个Process对象``>>>  `

All Coincidentally, either in heaven or is a man secretly working on it.

Guess you like

Origin www.cnblogs.com/ham-731/p/12121619.html