psutil模块功能介绍

API Reference

Exceptions

psutil.NoSuchProcess(pid, name=None, msg=None)

Raised when no process with the given PID is found in the current process list or when a process no longer exists (zombie).

psutil.AccessDenied(pid=None, name=None, msg=None)

Raised when permission to perform an action is denied.

psutil.TimeoutExpired(pid=None, name=None)

Raised on  Process.wait(timeout) if timeout expires and process is still alive.

New in 0.2.1

Classes

psutil.Process(pid)

A class which represents an OS process. Raises  NoSuchProcess if  pid does not exist.
Note that most of the methods of this class do not make sure the PID of the process being queried has been reused. That means you might end up retrieving an information referring to another process in case the original one this instance refers to is gone in the meantime. The only exceptions for which process identity is pre-emptively checked are:  parent, get_children(), set_nice(), suspend(), resume(), send_signal(), terminate() and  kill().
To prevent this problem for all other methods you can use  is_running() before querying the process or in case you're continuously iterating over a set of Process instances use  process_iter() which pre-emptively checks process identity for every yielded instance
  • pid
    The process pid.
  • ppid
    The process parent pid.
Changed in 0.5.0: return value is cached.
  • parent
    Return the parent process as a Process object pre-emptively checking whether PID has been reused.. If no ppid is known then return None.
  • name
    The process name.
Changed in 0.5.0: return value is cached.
  • exe
    The process executable as an absolute path name.
Changed in 0.5.0: return value is cached.
  • cmdline
    The command line process has been called with.
Changed in 0.5.0: return value is cached.
  • create_time
    The process creation time as a floating point number expressed in seconds since the epoch, in UTC.
    >>> import os, psutil, datetime
    >>> p = psutil.Process(os.getpid())
    >>> p.create_time
    1307289803.47
    >>> datetime.datetime.fromtimestamp(p.create_time).strftime("%Y-%m-%d %H:%M:%S")
    '2011-03-05 18:03:52'
Changed in 0.5.0: return value is cached.
  • uids
    The realeffective and saved user ids of the current process as a nameduple. This is the same as os.getresuid() but per-process.
New in 0.2.1
Availability:  UNIX
  • gids
    The realeffective and saved group ids of the current process as a nameduple. This is the same as os.getresgid() but per-process.
New in 0.2.1
Availability:
 UNIX
  • username
    The name of the user that owns the process. On UNIX this is calculated by using real process uid.
Changed in 2.0: Windows implementation has been rewritten in C for performace and pywin32 extension is no longer required.
  • terminal
    The terminal associated with this process, if any, else None. This is similar to "tty" command but per-process.
New in 0.3.0
Availability:
 UNIX
  • status
    The current process status. The return value is one of the STATUS_* constants (a lower cased string). Example:
    >>> import psutil, os
    >>> p = psutil.Process(os.getpid())
    >>> p.status
    'running'
    >>>
New in 0.2.1
Changed in 0.5.0
: the string representation can be used for comparison
  • nice
    A property getter/setter to get or set process niceness (priority). Deprecated in 0.5.0; use get_nice() and set_nice() instead.
New in 0.2.1
Deprecated in 0.5.0
  • get_nice()
  • set_nice(value)

    Get or set process niceness (priority). On UNIX this is a number which usually goes from -20 to 20. The higher the nice value, the lower the priority of the process.
    >>> p = psutil.Process(os.getpid())
    >>> p.get_nice()
    0
    >>> p.set_nice(10)
    >>>
On Windows this is available as well by using  GetPriorityClass and  SetPriorityClasspsutil.*_PRIORITY_CLASS constants (explained here) can be used in conjunction. Example which increases process priority:
>> p.set_nice(psutil.HIGH_PRIORITY_CLASS)
New in 0.5.0
  • as_dict(attrs=[], ad_value=None)
    Utility method returning process information as a hashable dictionary. If attrs is specified it must be a list of strings reflecting available Process class's attribute names (e.g. ['get_cpu_times', 'name']) else all public (read only) attributes are assumed. ad_value is the value which gets assigned to a dict key in case AccessDenied exception is raised when retrieving that particular process information.
New in 0.5.0
  • getcwd()
    Return a string representing the process current working directory.
Changed in 0.4.0: added FreeBSD support
Changed in 0.6.0: added OSX support
  • get_io_counters()
    Return process I/O statistics as a namedtuple including the number of read and write operations performed by the process and the amount of bytes read and written. For linux refer to /proc filesysem documentation. On BSD there's apparently no way to retrieve bytes counters, hence -1 is returned for read_bytes and write_bytes fields. OSX is not supported.
    >>> p.get_io_counters()
    io(read_count=454556, write_count=3456, read_bytes=110592, write_bytes=0)
New in 0.2.1
Availability:
 Linux, Windows, FreeBSD
  • get_ionice()
    Return process I/O niceness (priority) as a namedtuple including priority class and priority data. See set_ionice below for more information.
New in 0.2.1
Availability:
 Linux, Windows
Changed in 0.7.0: added Windows support.
  • set_ionice(ioclass, value=None)
    Change process I/O niceness (priority). ioclass is one of the IOPRIO_CLASS_* constants. value is a number which goes from 0 to 7. The higher value value, the lower the I/O priority of the process. For further information refer to ionice command line utility or ioprio_set system call. The example below sets IDLE priority class for the current process, meaning it will only get I/O time when no other process needs the disk:
    >>> p = psutil.Process(os.getpid())
    >>> p.set_ionice(psutil.IOPRIO_CLASS_IDLE)
    >>>
New in 0.2.1
Availability:
 Linux, Windows
  • get_num_fds()
    Return the number of file descriptors used by this process.
New in 0.5.0
Availability:  UNIX
  • get_num_handles()
    Return the number of handles used by this process.
New in 0.5.0
Availability:  Windows
  • get_num_threads()
    Return the number of threads used by this process.
  • get_threads()
    Return threads opened by process as a list of namedtuples including thread id and thread CPU times (user/system).
New in 0.2.1
  • get_num_ctx_switches()
    Return the number voluntary and involuntary context switches performed by this process.
New in 0.6.0
  • get_cpu_times()
    Return a tuple whose values are process CPU user and system times which means the amount of time expressed in seconds that a process has spent in user/system mode.
  • get_cpu_percent(interval=0.1)
    Return a float representing the process CPU utilization as a percentage. When interval is > 0.0 compares process times to system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares process times to system CPU times elapsed since last call, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. Example:
    >>> p = psutil.Process(os.getpid())
    >>> # blocking
    >>> p.get_cpu_percent(interval=1)
    2.0
    >>> # non-blocking (percentage since last call)
    >>> p.get_cpu_percent(interval=0)
    2.9
    >>>
Changed in 0.2.0: interval parameter was added
  • get_cpu_affinity()
  • set_cpu_affinity(cpus)
    Get and set process current CPU affinity. CPU affinity consists in telling the OS to run a certain process on a limited set of CPUs only. The number of eligible CPUs can be obtained with list(range(psutil.NUM_CPUS)).
    >>> psutil.NUM_CPUS
    4
    >>> p = psutil.Process(os.getpid())
    >>> p.get_cpu_affinity()
    [0, 1, 2, 3]
    >>> p.set_cpu_affinity([0])  # from now on, process will run on CPU #0 only
    >>>
New in 0.5.0
Availability:  Linux, Windows
  • get_rlimit(resource)
  • set_rlimit(resource, limits)
    Get and set process resource limits (see man prlimitresource is one of the psutil.RLIMIT_* constants. limits is a (soft, hard) tuple. Examples:
    >>> p = psutil.Process(os.getpid())
    >>> # process may open no more than 128 file descriptors
    >>> p.set_rlimit(psutil.RLIMIT_NOFILE, (128, 128))
    >>>
    >>> # process may create files no bigger than 1024 bytes
    >>> p.set_rlimit(psutil.RLIMIT_FSIZE, (1024, 1024))
    >>> 
New in 1.1.0
Availability:  Linux
  • get_memory_info()
    Return a tuple representing RSS (Resident Set Size) and VMS (Virtual Memory Size) in bytes.
    On UNIX RSS and VMS are the same values shown by ps. On Windows RSS and VMS refer to "Mem Usage" and "VM Size" columns of taskmgr.exe.
  • get_ext_memory_info()
    Return a namedtuple with variable fields depending on the platform representing extended memory information about the process. All numbers are expressed in bytes.
New in 0.6.0
  • get_memory_percent()
    Compare physical system memory to process resident memory (RSS) and calculate process memory utilization as a percentage.
  • get_memory_maps(grouped=True)
    Return process's mapped memory regions as a list of nameduples whose fields are variable depending on the platform. As such, portable applications should rely on namedtuple's path and rss fields only. This method is useful to obtain a detailed representation of process memory usage as explained here. If grouped is True the mapped regions with the same path are grouped together and the different memory fields are summed. If grouped is False every mapped region is shown as a single entity and the namedtuple will also include the mapped region's address space (addr) and permission set (perms).
    >>> p = psutil.Process(os.getpid())
    >>> p.get_memory_maps()
    [mmap(path='/lib/x86_64-linux-gnu/libutil-2.15.so', rss=16384, anonymous=8192, swap=0),
     mmap(path='/lib/x86_64-linux-gnu/libc-2.15.so', rss=6384, anonymous=15, swap=0),
     mmap(path='/lib/x86_64-linux-gnu/libcrypto.so.0.1', rss=34124, anonymous=1245, swap=0),
     mmap(path='[heap]', rss=54653, anonymous=8192, swap=0),
     mmap(path='[stack]', rss=1542, anonymous=166, swap=0),
     ...]
    >>> 
New in 0.5.0
  • get_children(recursive=False)
    Return the children of this process as a list of Process objects pre-emptively checking whether PID has been reused. If recursive is Truereturn all the parent descendants. Example (A == this process):
    A ─┐
       │
       ├─ B (child) ─┐
       │             └─ X (grandchild) ─┐
       │                                └─ Y (great grandchild)
       ├─ C (child)
       └─ D (child)
    
    >>> p.get_children()
    B, C, D
    >>> p.get_children(recursive=True)
    B, X, Y, C, D
Note that in the example above if process X disappears process Y won't be returned either as the reference to process A is lost.
Changed in 0.5.0: recursive parameter was added.
  • get_open_files()
    Return regular files opened by process as a list of namedtuples including file absolute path name and file descriptor. Example:
    >>> f = open('file.ext', 'w')
    >>> p = psutil.Process(os.getpid())
    >>> p.get_open_files()
    [openfile(path='/home/giampaolo/svn/psutil/file.ext', fd=3)]
Changed in 0.2.1: OSX implementation rewritten in C; no longer requiring lsof.
Changed in 0.4.1: FreeBSD implementation rewritten in C; no longer requiring lsof.
  • get_connections(kind='inet')
    Return all TCP and UDP connections opened by process as a list of namedtuples. Every namedtuple provides 6 attributes:

    • fd: the socket file descriptor. This can be passed to socket.fromfd to obtain a usable socket object. This is only available on UNIX; on Windows -1 is always returned.
    • family: the address family, either AF_INET or AF_INET6 
    • type: the address type, either SOCK_STREAM or SOCK_DGRAM 
    • laddr: the local address as a (ip, port) tuple. 
    • raddr: the remote address as a (ip, port) tuple. When the remote endpoint is not connected the tuple is empty. 
    • status: represents the status of a TCP connection. The return value is one of the psutil.CONN_* constants. For UDP and UNIX sockets this is always going to be psutil.CONN_NONE.
The kind parameter is a string which filters for connections that fit the following criteria:

Kind valueConnections using
inetIPv4 and IPv6
inet4IPv4
inet6IPv6
tcpTCP
tcp4TCP over IPv4
tcp6TCP over IPv6
udpUDP
udp4UDP over IPv4
udp6UDP over IPv6
unixUNIX socket (both UDP and TCP protocols)
allthe sum of all the possible families and protocols

Example:
>>> p = psutil.Process(1694)
>>> p.name
'firefox'
>>> p.get_connections()
[connection(fd=115, family=2, type=1, laddr=('10.0.0.1', 48776), raddr=('93.186.135.91', 80), status='ESTABLISHED'),
 connection(fd=117, family=2, type=1, laddr=('10.0.0.1', 43761), raddr=('72.14.234.100', 80), status='CLOSING'),
 connection(fd=119, family=2, type=1, laddr=('10.0.0.1', 60759), raddr=('72.14.234.104', 80), status='ESTABLISHED'),
 connection(fd=123, family=2, type=1, laddr=('10.0.0.1', 51314), raddr=('72.14.234.83', 443), status='SYN_SENT')]
On  FreeBSD this is implemented by parsing  lsof command output. If lsof is not installed on the system  NotImplementedError exception is raised and for third party processes (different than  os.getpid()) results can differ depending on user privileges.
Changed in 0.2.1: OSX implementation rewritten in C; no longer requiring lsof.
Changed in 0.4.0: added 'kind' parameter.
Changed in 0.6.0: added 'unix' socket support.
Changed in 0.6.0: BSD implementation rewritten in C; no longer requiring lsof.
Changed in 1.0.0: local_address and remote_address fields are deprecated.
Changed in 1.0.0: 'status' field is no longer a string but a constant object (psutil.CONN_*).
  • is_running()
    Return whether the current process is running in the current process list. This is reliable also in case the process is gone and its PID reused by another process, therefore it must be preferred over doing psutil.pid_exists(p.pid).
  • send_signal(signal)
    Send a signal to process (see signal module constants) pre-emptively checking whether PID has been reused. On Windows only SIGTERM is valid and is treated as an alias for kill().
  • suspend()
    Suspend process execution with SIGSTOP signal pre-emptively checking whether PID has been reused. On Windows this is done by suspending all process threads execution.
  • resume()
    Resume process execution with SIGCONT signal pre-emptively checking whether PID has been reused. On Windows this is done by resuming all process threads execution.
  • terminate()
    Terminate the process with SIGTERM signal pre-emptively checking whether PID has been reused. On Windows this is an alias for kill().
  • kill()
    Kill the current process by using SIGKILL signal pre-emptively checking whether PID has been reused.
Changed in 0.2.0: no longer accepts sig keyword argument - use send_signal() instead.
  • wait(timeout=None)
    Wait for process termination and if the process is a children of the current one also return the exit code, else None. On Windows there's no such limitation (exit code is always returned). If the process is already terminated does not raise NoSuchProcess exception but just returnNone immediately. If timeout is specified and process is still alive raises TimeoutExpired exception.
New in 0.2.1
Changed in 0.4.0
: timeout=0 can now be used to make wait() return immediately (non blocking)



psutil.Popen(*args, **kwargs)

A more convenient interface to stdlib  subprocess.Popen. It starts a sub process and deals with it exactly as when using subprocess.Popen class but in addition also provides all the properties and methods of psutil.Process class in a single interface. For method names common to both classes such as  kill() and  terminate(), psutil.Process implementation takes precedence. For a complete documentation refers to  subprocess module documentation.
>>> import psutil
>>> from subprocess import PIPE
>>> p = psutil.Popen(["/usr/bin/python", "-c", "print 'hi'"], stdout=PIPE)
>>> p.name
'python'
>>> p.uids
user(real=1000, effective=1000, saved=1000)
>>> p.username
'giampaolo'
>>> p.communicate()
('hi\n', None)
>>> p.wait(timeout=2)
0
>>>
New in 0.2.1

System related functions

Processes

psutil.get_pid_list()

Return a list of current running PIDs.

psutil.pid_exists(pid)

Check whether the given PID exists in the current process list. This is faster than doing  pid in psutil.get_pid_list() and should be preferred.

psutil.process_iter()

Return an iterator yielding a Process class instances for all running processes on the local machine. Every new Process instance is only created once and then cached into an internal table which is updated every time this is used. As such it must be preferred over doing  for pid in psutil.get_pid_list(): psutil.Process(pid) as it's optimized and avoids to maintain a separate process table in your code. Cached Process instances are checked for identity so that you're safe in case a PID has been reused by another process, in which case the cached instance is updated. Sorting order in which processes are returned is based on their PID.

Changed in 0.5.0: added internal cache
Changed in 0.6.0: yields processes sorted by their PIDs

psutil.wait_procs(procs, timeout, callback=None)

Convenience function which waits for a list of processes to terminate. Return a  (gone, alive) tuple indicating which processes are gone and which ones are still alive. The gone ones will have a new 'retcode' attribute indicating process exit status (may be  None). callback is a callable function which gets called every time a process terminates (a  Process instance is passed as callback argument). Function will return as soon as all processes terminate or when timeout occurs. Tipical use case is:
  • send SIGTERM to a list of processes
  • give them some time to terminate
  • send SIGKILL to those ones which are still alive
Example:

def on_terminate(proc):
    print("process {} terminated".format(proc))

for p in procs:
   p.terminate()
gone, alive = wait_procs(procs, 3, callback=on_terminate)
for p in alive:
    p.kill()
New in 1.2.0

psutil.get_process_list()

Same as  process_iter() but return a list instead.

Deprecated in 0.5.0

CPU

psutil.cpu_percent(interval=0.1, percpu=False)

Return a float representing the current system-wide CPU utilization as a percentage. When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls.
When  percpu is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls.

>>> # blocking, system-wide
>>> psutil.cpu_percent(interval=1)
2.0
>>>
>>> # blocking, per-cpu
>>> psutil.cpu_percent(interval=1, percpu=True)
[2.0, 1.0]
>>>
>>> # non-blocking (percentage since last call)
>>> psutil.cpu_percent(interval=0)
2.9
>>>
Changed in 0.2.0: interval parameter was added
Changed in 0.3.0: percpu parameter was added

psutil.cpu_times(percpu=False)

Return system CPU times as a namedtuple. Every attribute represents the time CPU has spent in the given mode.
The attributes availability varies depending on the platform. Here follows a list of all available attributes:
  • user
  • system
  • idle
  • nice (UNIX)
  • iowait (Linux)
  • irq (Linux, FreeBSD)
  • softirq (Linux)
  • steal (Linux >= 2.6.11)
  • guest (Linux >= 2.6.24)
  • guest_nice (Linux >= 3.2.0)

When  percpu is True return a list of nameduples for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls.
Changed in 0.3.0: percpu parameter was added
Changed in 0.7.0: added 'steal', 'guest', and 'guest_nice'

psutil.cpu_times_percent(interval=0.1, percpu=False)

Same as  cpu_percent() but provides utilization percentages for each specific CPU time as is returned by  cpu_times()interval and percpu arguments have the same meaning as in  cpu_percent().

Added in 0.7.0.

Memory

psutil.virtual_memory()

Return statistics about system memory usage as a namedtuple including the following fields, expressed in bytes:
  • total: total physical memory available
  • available: the actual amount of available memory that can be given instantly to processes that request more memory in bytes; this is calculated by summing different memory values depending on the platform (e.g. free + buffers + cached on Linux) and it is supposed to be used to monitor actual memory usage in a cross platform fashion.
  • percent: the percentage usage calculated as (total - available) / total * 100
  • used: memory used, calculated differently depending on the platform and designed for informational purposes only.
  • free: memory not being used at all (zeroed) that is readily available; note that this doesn't reflect the actual memory available (use 'available' instead).

Platform-specific fields:
  • active (UNIX): memory currently in use or very recently used, and so it is in RAM.
  • inactive (UNIX): memory that is marked as not used.
  • buffers (Linux, BSD): cache for things like file system metadata.
  • cached (Linux, BSD): cache for various things.
  • wired (BSD, OSX): memory that is marked to always stay in RAM. It is never moved to disk.
  • shared (BSD): memory that may be simultaneously accessed by multiple processes.
The sum of 'used' and 'available' does not necessarily equal total. On Windows 'available' and 'free' are the same.
>>> psutil.virtual_memory()
vmem(total=8374149120L, available=1247768576L, percent=85.1, used=8246628352L, free=127520768L, active=3208777728, inactive=1133408256, buffers=342413312L, cached=777834496)
New in 0.6.0

psutil.swap_memory()

Return system swap memory statistics as a namedtuple including the following attributes:
  • total: total swap memory in bytes
  • used: used swap memory in bytes
  • free: free swap memory in bytes
  • percent: the percentage usage
  • sin: no. of bytes the system has swapped in from disk (cumulative)
  • sout: no. of bytes the system has swapped out from disk (cumulative)

'sin' and 'sout' on Windows are meaningless and always set to 0.
>>> psutil.swap_memory()
swap(total=2097147904L, used=886620160L, free=1210527744L, percent=42.3, sin=1050411008, sout=1906720768)
New in 0.6.0

psutil.phymem_usage()
psutil.virtmem_usage()
psutil.cached_phymem()
psutil.phymem_buffers()
psutil.avail_phymem()
psutil.used_phymem()
psutil.total_virtmem()
psutil.avail_virtmem()
psutil.used_virtmem()

These functions are deprecated by  psutil.virtual_memory() and  psutil.swap_memory(). Use them instead.

Deprecated in 0.3.0 and 0.6.0

Disks

psutil.disk_partitions(all=False)

Return all mounted disk partitions as a list of namedtuples including device, mount point and filesystem type, similarly to "df" command on posix. 
If  all parameter is False return physical devices only (e.g. hard disks, cd-rom drives, USB keys) and ignore all others (e.g. memory partitions such as  /dev/shm).
Namedtuple's 'fstype' field is a string which varies depending on the platform. 
On Linux it can be one of the values found in /proc/filesystems (e.g. 'ext3' for an ext3 hard drive o 'iso9660' for the CD-ROM drive). 
On Windows it is determined via  GetDriveType and can be either "removable", "fixed", "remote", "cdrom", "unmounted" or "ramdisk". 
On OSX and FreeBSD it is retrieved via  getfsstat(2)
See  examples/disk_usage.py script providing an example usage.

>>> psutil.disk_partitions()
[partition(device='/dev/sda3', mountpoint='/', fstype='ext4', opts='rw,errors=remount-ro'),
 partition(device='/dev/sda7', mountpoint='/home', fstype='ext4', opts='rw')]
>>>
New in 0.3.0
Changed in 0.5.0
: namedtuple now includes a new 'opts' field

psutil.disk_usage(path)

Return disk usage statistics about the given  path as a namedtuple including total, used and free space expressed in bytes plus the percentage usage. OSError is raised if path does not exist. See  examples/disk_usage.py script providing an example usage.

>>> psutil.disk_usage('/')
usage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
New in 0.3.0

psutil.disk_io_counters(perdisk=False)

Return system disk I/O statistics as a namedtuple including the following attributes:
  • read_count: number of reads
  • write_count: number of writes
  • read_bytes: number of bytes read
  • write_bytes: number of bytes written
  • read_time: time spent reading from disk (in milliseconds)
  • write_time: time spent writing to disk (in milliseconds)

If perdisk is True return the same information for every physical disk installed on the system as a dictionary with partition ames as the keys and the namedutuple described above as the values.
>>> psutil.disk_io_counters()
iostat(read_count=8141, write_count=2431, read_bytes=290203, write_bytes=537676, read_time=5868, write_time=94922)
>>>
>>> psutil.disk_io_counters(perdisk=True)
{'sda1': iostat(read_count=920, write_count=1, read_bytes=2933248, write_bytes=512, read_time=6016, write_time=4),
 'sda2': iostat(read_count=18707, write_count=8830, read_bytes=6060, write_bytes=3443, read_time=24585, write_time=1572),
 'sdb1': iostat(read_count=161, write_count=0, read_bytes=786432, write_bytes=0, read_time=44, write_time=0)}
New in 0.4.0

Network

psutil.net_io_counters(pernic=False)

Return network I/O statistics as a namedtuple including the following attributes:
  • bytes_sent: number of bytes sent
  • bytes_recv: number of bytes received
  • packets_sent: number of packets sent
  • packets_recv: number of packets received
  • errin: total number of errors while receiving
  • errout: total number of errors while sending
  • dropin: total number of incoming packets which were dropped
  • dropout: total number of outgoing packets which were dropped (always 0 on OSX and BSD)

If pernic is True return the same information for every network interface installed on the system as a dictionary with network interface names as the keys and the namedtuple described above as the values.
>>> psutil.network_io_counters()
iostat(bytes_sent=14508483, bytes_recv=62749361, packets_sent=84311, packets_recv=94888, errin=0, errout=0, dropin=0, dropout=0)
>>>
>>> psutil.network_io_counters(pernic=True)
{'lo': iostat(bytes_sent=547971, bytes_recv=547971, packets_sent=5075, packets_recv=5075, errin=0, errout=0, dropin=0, dropout=0),
 'wlan0': iostat(bytes_sent=13921765, bytes_recv=62162574, packets_sent=79097, packets_recv=89648, errin=0, errout=0, dropin=0, dropout=0)}
New in 0.4.0
Changed in 0.6.0:
 added errin, errout, dropin, dropout fields

psutil.network_io_counters(pernic=False)

Old name for net_io_counters().

Deprecated in 1.0.0

Other system info

psutil.get_users()

Return users currently connected on the system as a list of namedtuples including the following attributes:
  • user: the name of the user
  • terminal: the tty or pseudo-tty associated with the user, if any.
  • host: the host name associated with the entry, if any.
  • started: the creation time as a floating point number expressed in seconds since the epoch.

>>> psutil.get_users()
[user(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0),
 user(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0)]
New in 0.5.0

psutil.get_boot_time()()

Return the system boot time expressed in seconds since the epoch. This is also available as  psutil.BOOT_TIME but reflects system clock updates.


Constants

psutil.TOTAL_PHYMEM

The amount of total physical memory on the system, in bytes. This is the same as  psutil.virtual_memory().total.

psutil.NUM_CPUS

The number of CPUs on the system. This is preferable than using  os.environ['NUMBER_OF_PROCESSORS'] as it is more accurate and always available.

psutil.BOOT_TIME

A number indicating the system boot time expressed in seconds since the epoch.

New in 0.2.1
Deprecated in 0.7.0: use psutil.get_boot_time()

psutil.ABOVE_NORMAL_PRIORITY_CLASS
psutil.BELOW_NORMAL_PRIORITY_CLASS
psutil.HIGH_PRIORITY_CLASS
psutil.IDLE_PRIORITY_CLASS
psutil.NORMAL_PRIORITY_CLASS
psutil.REALTIME_PRIORITY_CLASS

A set of integers representing the priority of a process on Windows (see  MSDN documentation). They can be used in conjunction with psutil.Process.nice to get or set process priority.

New in 0.2.1
Availability:
 Windows

psutil.IOPRIO_CLASS_NONE
psutil.IOPRIO_CLASS_RT
psutil.IOPRIO_CLASS_BE
psutil.IOPRIO_CLASS_IDLE

A set of integers representing the I/O priority of a process on Linux. They can be used in conjunction with psutil.Process.get_ionice() and  psutil.Process.set_ionice() to get or set process I/O priority. For further information refer to ionice command line utility or  ioprio_get system call.

New in 0.2.1
Availability:
 Linux

psutil.RLIMIT_INFINITY
psutil.RLIMIT_AS
psutil.RLIMIT_CORE
psutil.RLIMIT_CPU
psutil.RLIMIT_DATA
psutil.RLIMIT_FSIZE
psutil.RLIMIT_LOCKS
psutil.RLIMIT_MEMLOCK
psutil.RLIMIT_MSGQUEUE
psutil.RLIMIT_NICE
psutil.RLIMIT_NOFILE
psutil.RLIMIT_NPROC
psutil.RLIMIT_RSS
psutil.RLIMIT_RTPRIO
psutil.RLIMIT_RTTIME
psutil.RLIMIT_RTPRIO
psutil.RLIMIT_SIGPENDING
psutil.RLIMIT_STACK

Constants used for getting and setting process resource limits to be used in conjunction with  psutil.Process.get_rlimit() and psutil.Process.set_rlimit(). See  man prlimit for futher information.

New in 1.1.0
Availability:
 Linux

psutil.STATUS_RUNNING
psutil.STATUS_SLEEPING
psutil.STATUS_DISK_SLEEP
psutil.STATUS_STOPPED
psutil.STATUS_TRACING_STOP
psutil.STATUS_ZOMBIE
psutil.STATUS_DEAD
psutil.STATUS_WAKE_KILL
psutil.STATUS_WAKING
psutil.STATUS_IDLE
psutil.STATUS_LOCKED
psutil.STATUS_WAITING

A set of integers representing the status of a process. To be used in conjunction with  psutil.Process.status property.

New in 0.2.1
Changed in 1.1.0:
 turned into python strings (instead of int-like objects with a nice str() representation)

psutil.CONN_ESTABLISHED
psutil.CONN_SYN_SENT
psutil.CONN_SYN_RECV
psutil.CONN_FIN_WAIT1
psutil.CONN_FIN_WAIT2
psutil.CONN_TIME_WAIT
psutil.CONN_CLOSE
psutil.CONN_CLOSE_WAIT
psutil.CONN_LAST_ACK
psutil.CONN_LISTEN
psutil.CONN_CLOSING
psutil.CONN_NONE
psutil.CONN_DELETE_TCB (Windows only)
psutil.CONN_IDLE (Solaris only)
psutil.CONN_BOUND (Solaris only)

TCP connection status as returned by  Process.get_connections()'s  status field. If used with str() return a human-readable status string. The str() representation can also be used for comparison.

New in 1.0.0
Changed in 1.1.0:
 turned into python strings (instead of int-like objects with a nice str() representation)
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值