psutil--跨平臺的進程管理

Python處理Windows進程

psutil(Python system and process utilities)是一個跨平臺的進程管理和系統(tǒng)工具的python庫,
可以處理系統(tǒng)CPU晋被,memory,disks,network等信息。主要用于系統(tǒng)資源的監(jiān)控煌恢,分析骗卜,以及對進程
進行一定的管理宠页。通過psutil可以實現(xiàn)如ps,top寇仓,lsof举户,netstat,ifconfig遍烦, who俭嘁,df,kill服猪,free供填,
nice拐云,ionice,iostat近她,iotop叉瘩,uptime,pidof粘捎,tty薇缅,taskset,pmap晌端。在Linux捅暴,windows,OSX咧纠,freebsd
Sun Solaris等系統(tǒng)上工作蓬痒,最新的版本python是要高于2.6(Python 2.4 Python2.5 可以用2.1.3版本)

系統(tǒng)相關的功能

CPU相關

psutil.cpu_times(precpu=False)
返回系統(tǒng)CPU運行時間的元組,時間為秒漆羔。

  • user
 - system
 - 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+ )

psutil.cpu_percent(interval=None, percpu=False)
返回一個浮點書梧奢,代表當前cpu的利用率的百分比,包括sy+user. 當interval為0或者None時演痒,表示的是interval時間內(nèi)的sys的利用率亲轨。
當percpu為True返回是每一個cpu的利用率。

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

psutil.cpu_count(logical=True)

Memory

psutil.virtual_memory()

返回一個內(nèi)存信息的元組鸟顺,大小為字節(jié)

total: 內(nèi)存的總大小.
available: 可以用來的分配的內(nèi)存惦蚊,不同系統(tǒng)計算方式不同; Linux下的計算公式:free+ buffers + cached
percent: 已經(jīng)用掉內(nèi)存的百分比 (total - available) / total * 100.
used: 已經(jīng)用掉內(nèi)存大小讯嫂,不同系統(tǒng)計算方式不同
free: 空閑未被分配的內(nèi)存蹦锋,Linux下不包括buffers和cached

Platform-specific fields:

active: (UNIX): 最近使用內(nèi)存和正在使用內(nèi)存。
inactive: (UNIX): 已經(jīng)分配但是沒有使用的內(nèi)存
buffers: (Linux, BSD): 緩存欧芽,linux下的Buffers
cached:(Linux, BSD): 緩存莉掂,Linux下的cached.
wired: (BSD, OSX): 一直存在于內(nèi)存中的部分,不會被移除
shared: (BSD): 緩存

內(nèi)存總大小不等于Used+available,在windows系統(tǒng)可用內(nèi)存和空閑內(nèi)存是用一個千扔。具體的可以examples/meminfo.py憎妙。

psutil.swap_memory()
返回系統(tǒng)的swap信息

total: swap的總大小 單位為字節(jié)
used: 已用的swap大小 bytes
free: 空閑的swap大小 bytes
percent: 已用swap的百分比
sin: 從磁盤調(diào)入是swap的大小
sout: 從swap調(diào)出到disk的大小

sin, sout在windows沒有意義曲楚。

Disks

psutil.disk_partitions(all=False)
返回所有掛載的分區(qū)的信息的列表厘唾,列表中的每一項類似于df命令的格式輸出,包括分區(qū)龙誊,掛載點抚垃,文件系統(tǒng)格式,掛載參數(shù)等,會忽略掉/dev/shm,/proc/filesystem等讯柔,windows上分區(qū)格式 "removable", "fixed", "remote", "cdrom", "unmounted" or "ramdisk"。

>>>
>>> import psutil
>>> psutil.disk_partitions()
[sdiskpart(device='/dev/sda3', mountpoint='/', fstype='ext4', opts='rw,errors=remount-ro'),
 sdiskpart(device='/dev/sda7', mountpoint='/home', fstype='ext4', opts='rw')]

psutil.disk_usage(path)
返回硬盤护昧,分區(qū)或者目錄的使用情況魂迄,單位字節(jié)
如果不存在會報“OSError”錯誤。

>>>
>>> import psutil
>>> psutil.disk_usage('/')
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)

psutil.disk_io_counters(perdisk=False)
返回當前磁盤的io情況

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 names as the keys and the namedutuple described above as the values. See examples/iotop.py for an example application.

>>>
>>> import psutil
>>> psutil.disk_io_counters()
sdiskio(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': sdiskio(read_count=920, write_count=1, read_bytes=2933248, write_bytes=512, read_time=6016, write_time=4),
 'sda2': sdiskio(read_count=18707, write_count=8830, read_bytes=6060, write_bytes=3443, read_time=24585, write_time=1572),
 'sdb1': sdiskio(read_count=161, write_count=0, read_bytes=786432, write_bytes=0, read_time=44, write_time=0)}

Network

psutil.net_io_counters(pernic=False)
返回整個系統(tǒng)的網(wǎng)絡信息

bytes_sent: 發(fā)送的字節(jié)數(shù)
bytes_recv: 接收的字節(jié)數(shù)
packets_sent: 發(fā)送到數(shù)據(jù)包的個數(shù)
packets_recv: 接受的數(shù)據(jù)包的個數(shù)
errin:
errout: 發(fā)送數(shù)據(jù)包錯誤的總數(shù)
dropin: 接收時丟棄的數(shù)據(jù)包的總數(shù)
dropout: 發(fā)送時丟棄的數(shù)據(jù)包的總數(shù)(OSX和BSD系統(tǒng)總是0)

如果 pernic值為True惋耙,會顯示具體各個網(wǎng)卡的信息捣炬。

>>>
>>> import psutil
>>> psutil.net_io_counters()
snetio(bytes_sent=14508483, bytes_recv=62749361, packets_sent=84311, packets_recv=94888, errin=0, errout=0, dropin=0, dropout=0)
>>>
>>> psutil.net_io_counters(pernic=True)
{'lo': snetio(bytes_sent=547971, bytes_recv=547971, packets_sent=5075, packets_recv=5075, errin=0, errout=0, dropin=0, dropout=0),
'wlan0': snetio(bytes_sent=13921765, bytes_recv=62162574, packets_sent=79097, packets_recv=89648, errin=0, errout=0, dropin=0, dropout=0)}

psutil.net_connections(kind='inet')
返回系統(tǒng)的整個socket連接的信息,可以選擇查看哪些類型的連接信息绽榛,類似于netstat命令

fd:
family: the address family, either AF_INET, AF_INET6 or AF_UNIX.
type: the address type, either SOCK_STREAM or SOCK_DGRAM.
laddr: the local address as a (ip, port) tuple or a path in case of AF_UNIX sockets.
raddr: the remote address as a (ip, port) tuple or an absolute path in case of UNIX sockets. When the remote endpoint is not connected you’ll get an empty tuple (AF_INET) or None (AF_UNIX). On Linux AF_UNIX sockets will always have this set to None.
status: represents the status of a TCP connection. The return value is one of the psutil.CONN_
constants (a string). For UDP and UNIX **sockets this is always going to be psutil.CONN_NONE.
pid: the PID of the process which opened the socket, if retrievable, else None. On some platforms (e.g. Linux) the availability of this field **changes depending on process privileges (root is needed).

參數(shù)kind的類型:
“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()
[pconn(fd=115, family=2, type=1, laddr=('10.0.0.1', 48776), raddr=('93.186.135.91', 80), status='ESTABLISHED', pid=1254),
 pconn(fd=117, family=2, type=1, laddr=('10.0.0.1', 43761), raddr=('72.14.234.100', 80), status='CLOSING', pid=2987),
 pconn(fd=-1, family=2, type=1, laddr=('10.0.0.1', 60759), raddr=('72.14.234.104', 80), status='ESTABLISHED', pid=None),
 pconn(fd=-1, family=2, type=1, laddr=('10.0.0.1', 51314), raddr=('72.14.234.83', 443), status='SYN_SENT', pid=None)
 ...]

Other system info

psutil.users()
返回當前系統(tǒng)用戶登錄信息

user: 用戶的名稱
terminal: 運行終端湿酸,tty還是pts等
host: 登錄的IP
started: 登錄了多長時間

>>>
>>> import psutil
>>> psutil.users()
[suser(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0),
 suser(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0)]

psutil.boot_time()
返回當前的時間

>>>
>>> import psutil, datetime
>>> psutil.boot_time()
1389563460.0
>>> datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
'2014-01-12 22:51:00'

Processes

Functions

psutil.pids()
返回當前運行的進程pid列表

psutil.pid_exists(pid)
是否存在次pid,快速的驗證方式pid in psutil.pids()

psutil.process_iter()
返回一個包含Process對象的迭代器灭美。每一個對象只創(chuàng)建一次推溃,創(chuàng)建后緩存起來。當一個進程更新時届腐,會更新緩存铁坎。遍歷所有進程首選psutil.pids().迭代器排序是根據(jù)pid。

import psutil

for proc in psutil.process_iter():
    try:
        pinfo = proc.as_dict(attrs=['pid', 'name'])
    except psutil.NoSuchProcess:
        pass
    else:
        print(pinfo)

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

Convenience function which waits for a list of Process instances 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 returncode attribute indicating process exit status (it may be None). callback is a 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:

import psutil

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

procs = [...]  # a list of Process instances
for p in procs:
    p.terminate()
gone, alive = wait_procs(procs, timeout=3, callback=on_terminate)
for p in alive:
    p.kill()

Exceptions

class psutil.Error
基礎異常犁苏,psutil的其他異常都繼承這個

class psutil.NoSuchProcess(pid, name=None, msg=None)
當進程不在進程列表中硬萍,或者進程不存在時觸發(fā)。

class psutil.AccessDenied(pid=None, name=None, msg=None)
沒有權(quán)限時围详,被觸發(fā)

class psutil.TimeoutExpired(seconds, pid=None, name=None, msg=None)
當Process.wait() 超時朴乖,并且Process 一直在運行時.

psutil

標簽(空格分隔): Python


Process class

class psutil.Process(pid=None)
Process類是一個帶有pid的進程。如果沒有指定pid助赞,則默認的進程為os.getpid()所得進程买羞。Process會觸發(fā)NoSuchProcess(當進程不存在時)和AccessDenied異常,

注意

Process是通過pid綁定的嫉拐。如果在一個Process實例哩都,在psutil運行中pid進程死掉,而
這個pid又綁定給了別的新的進程婉徘。為了保證Process的安全性可以通過pid+createion time
方式來確認進程是否是同一個漠嵌。

pid
進程的PID

ppid()
父進程pid. On Windows the return value is cached after first call.

name()
進程名.

exe()
進程運行命令的絕對路徑。

cmdline()
The command line this process has been called with.

create_time()
進程創(chuàng)建時間

>>>
>>> import psutil, datetime
>>> p = psutil.Process()
>>> p.create_time()
1307289803.47
>>> datetime.datetime.fromtimestamp(p.create_time()).strftime("%Y-%m-%d %H:%M:%S")
'2011-03-05 18:03:52'

as_dict(attrs=None, ad_value=None)
返回進程信息的哈希字典的實用方法盖呼,attrs指定的值必須是Process的屬性值儒鹿,例如(['cpu_times','name'])

>>>
>>> import psutil
>>> p = psutil.Process()
>>> p.as_dict(attrs=['pid', 'name', 'username'])
{'username': 'giampaolo', 'pid': 12366, 'name': 'python'}

parent()
返回父進程,如果不存在父進程几晤,則返回None约炎。

status()
進程當前運行狀態(tài),string形式。

cwd()
進程運行的所在的目錄

username()
哪個用戶下運行的進程

uids()
返回real=uid圾浅,effective掠手,saved用戶的uid

Availability: UNIX

gids()

Availability: UNIX

terminal()
The terminal associated with this process, if any, else None. This is similar to “tty” command but can be used for every process PID.

Availability: UNIX

nice(value=None)
獲取或者設置進程的nice值,

>>>
>>> import psutil
>>> p = psutil.Process()
>>> p.nice(10)  # set
>>> p.nice()  # get
10
>>>

在windows系統(tǒng)上狸捕,只能通過GetProrityClassSetPriorityClasspsutil.*_PRIORITY_CLASS包含的值來設定

>>>
>>> p.nice(psutil.HIGH_PRIORITY_CLASS)

ionice(ioclass=None, value=None)
獲取或者設置進程I/O的優(yōu)先級喷鸽。Linux上的ioclass的值psutil.IOPRO_CLASS_*值在0-7,windows 2 為正常灸拍,1為優(yōu)先級低做祝,0為非常低。

>>>
>>> import psutil
>>> p = psutil.Process()
>>> p.ionice(psutil.IOPRIO_CLASS_IDLE)  # set
>>> p.ionice()  # get
pionice(ioclass=3, value=0)
>>>

rlimit(resource, limits=None)
Get or set process resource limits (see man prlimit). resource is one of the psutil.RLIMIT_* constants. limits is a (soft, hard) tuple. This is the same as resource.getrlimit() and resource.setrlimit() but can be used for every process PID and only on Linux. Example:

>>>
>>> import psutil
>>> p = psutil.Process()
>>> # process may open no more than 128 file descriptors
>>> p.rlimit(psutil.RLIMIT_NOFILE, (128, 128))
>>> # process may create files no bigger than 1024 bytes
>>> p.rlimit(psutil.RLIMIT_FSIZE, (1024, 1024))
>>> # get
>>> p.rlimit(psutil.RLIMIT_FSIZE)
(1024, 1024)
>>>

Availability: Linux

io_counters()
返回這個進程的IO情況

>>>
>>> import psutil
>>> p = psutil.Process()
>>> p.io_counters()
pio(read_count=454556, write_count=3456, read_bytes=110592, write_bytes=0)

Availability: all platforms except OSX

num_ctx_switches()
The number voluntary and involuntary context switches performed by this process.

num_fds()
The number of file descriptors used by this process.

Availability: UNIX

num_handles()
The number of handles used by this process.

Availability: Windows

num_threads()
The number of threads currently used by this process.

threads()
Return threads opened by process as a list of namedtuples including thread id and thread CPU times (user/system).

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. This is similar to os.times() but can be used for every process PID.

cpu_percent(interval=None)
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. That means the first time this is called it will return a meaningless 0.0 value which you are supposed to ignore. In this case is recommended for accuracy that this function be called a second time with at least 0.1 seconds between calls. Example:

>>>
>>> import psutil
>>> p = psutil.Process()
>>>
>>> # blocking
>>> p.cpu_percent(interval=1)
2.0
>>> # non-blocking (percentage since last call)
>>> p.cpu_percent(interval=None)
2.9
>>>

Note a percentage > 100 is legitimate as it can result from a process with multiple threads running on different CPU cores.
Warning the first time this method is called with interval = 0.0 or None it will return a meaningless 0.0 value which you are supposed to ignore.
cpu_affinity(cpus=None)
Get or 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.cpu_count())).

>>>
>>> import psutil
>>> psutil.cpu_count()
4
>>> p = psutil.Process()
>>> p.cpu_affinity()  # get
[0, 1, 2, 3]
>>> p.cpu_affinity([0])  # set; from now on, process will run on CPU #0 only
>>> p.cpu_affinity()
[0]
>>>
>>> # reset affinity against all CPUs
>>> all_cpus = list(range(psutil.cpu_count()))
>>> p.cpu_affinity(all_cpus)
>>>

Availability: Linux, Windows, BSD

Changed in version 2.2.0: added support for FreeBSD

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. For more detailed memory stats use memory_info_ex().

memory_info_ex()
Return a namedtuple with variable fields depending on the platform representing extended memory information about the process. All numbers are expressed in bytes.

Linux OSX BSD SunOS Windows
rss rss rss rss num_page_faults
vms vms vms vms peak_wset
shared pfaults text wset
text pageins data peak_paged_pool
lib stack paged_pool
data peak_nonpaged_pool
dirty nonpaged_pool
pagefile
peak_pagefile
private

Windows metrics are extracted from PROCESS_MEMORY_COUNTERS_EX structure. Example on Linux:

>>>
>>> import psutil
>>> p = psutil.Process()
>>> p.memory_info_ex()
pextmem(rss=15491072, vms=84025344, shared=5206016, text=2555904, lib=0, data=9891840, dirty=0)

memory_percent()
Compare physical system memory to process resident memory (RSS) and calculate process memory utilization as a percentage.

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). See examples/pmap.py for an example application.

>>>
>>> import psutil
>>> p = psutil.Process()
>>> p.memory_maps()
[pmmap_grouped(path='/lib/x8664-linux-gnu/libutil-2.15.so', rss=16384, anonymous=8192, swap=0),
 pmmap_grouped(path='/lib/x8664-linux-gnu/libc-2.15.so', rss=6384, anonymous=15, swap=0),
 pmmap_grouped(path='/lib/x8664-linux-gnu/libcrypto.so.0.1', rss=34124, anonymous=1245, swap=0),
 pmmap_grouped(path='[heap]', rss=54653, anonymous=8192, swap=0),
 pmmap_grouped(path='[stack]', rss=1542, anonymous=166, swap=0),
 ...]
>>>

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 True return all the parent descendants. Example assuming A == this process:

A ─┐

├─ B (child) ─┐
│ └─ X (grandchild) ─┐
│ └─ Y (great grandchild)
├─ C (child)
└─ D (child)

>>> p.children()
B, C, D
>>> p.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.

open_files()
Return regular files opened by process as a list of namedtuples including the absolute file name and the file descriptor number (on Windows this is always -1). Example:

>>>
>>> import psutil
>>> f = open('file.ext', 'w')
>>> p = psutil.Process()
>>> p.open_files()
[popenfile(path='/home/giampaolo/svn/psutil/file.ext', fd=3)]

connections(kind="inet")
Return socket connections opened by process as a list of namedutples. To get system-wide connections use psutil.net_connections(). 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, AF_INET6 or AF_UNIX.
type: the address type, either SOCK_STREAM or SOCK_DGRAM.
laddr: the local address as a (ip, port) tuple or a path in case of AF_UNIX sockets.
raddr: the remote address as a (ip, port) tuple or an absolute path in case of UNIX sockets. When the remote endpoint is not connected you’ll get an empty tuple (AF_INET) or None (AF_UNIX). On Linux AF_UNIX sockets will always have this set to None.
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 value Connections using
“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

Example:

>>>
>>> import psutil
>>> p = psutil.Process(1694)
>>> p.name()
'firefox'
>>> p.connections()
[pconn(fd=115, family=2, type=1, laddr=('10.0.0.1', 48776), raddr=('93.186.135.91', 80), status='ESTABLISHED'),
 pconn(fd=117, family=2, type=1, laddr=('10.0.0.1', 43761), raddr=('72.14.234.100', 80), status='CLOSING'),
 pconn(fd=119, family=2, type=1, laddr=('10.0.0.1', 60759), raddr=('72.14.234.104', 80), status='ESTABLISHED'),
 pconn(fd=123, family=2, type=1, laddr=('10.0.0.1', 51314), raddr=('72.14.234.83', 443), status='SYN_SENT')]

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).

Note this will return True also if the process is a zombie (p.status() == psutil.STATUS_ZOMBIE).
send_signal(signal)
發(fā)送新號給進程
Send a signal to process (see signal module constants) pre-emptively checking whether PID has been reused. This is the same as os.kill(pid, sig). 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 UNIX this is the same as os.kill(pid, signal.SIGSTOP). 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 UNIX this is the same as os.kill(pid, signal.SIGCONT). 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 UNIX this is the same as os.kill(pid, signal.SIGTERM). 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. On UNIX this is the same as os.kill(pid, signal.SIGKILL). On Windows this is done by using TerminateProcess.

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 immediately return None instead of raising NoSuchProcess. If timeout is specified and process is still alive raise TimeoutExpired exception. It can also be used in a non-blocking fashion by specifying timeout=0 in which case it will either return immediately or raise TimeoutExpired. To wait for multiple processes use psutil.wait_procs().

Popen class

class 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 but in addition it also provides all the methods of psutil.Process class in a single interface. For method names common to both classes such as send_signal(), terminate() and kill() psutil.Process implementation takes precedence. For a complete documentation refer to subprocess module documentation.

Note Unlike subprocess.Popen this class pre-emptively checks wheter PID has been reused on send_signal(), terminate() and kill() so that you don’t accidentally terminate another process, fixing http://bugs.python.org/issue6973.

>>>
>>> import psutil
>>> from subprocess import PIPE
>>>
>>> p = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"], stdout=PIPE)
>>> p.name()
'python'
>>> p.username()
'giampaolo'
>>> p.communicate()
('hello\n', None)
>>> p.wait(timeout=2)
0
>>>

Constants

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 strings representing the status of a process. Returned by psutil.Process.status().

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)
psutil.CONN_IDLE(Solaris)
psutil.CONN_BOUND(Solaris)

A set of strings representing the status of a TCP connection. Returned by psutil.Process.connections() (status field).

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.

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.ionice() to get or set process I/O priority. IOPRIO_CLASS_NONE and IOPRIO_CLASS_BE (best effort) is the default for any process that hasn’t set a specific I/O priority. IOPRIO_CLASS_RT (real time) means the process is given first access to the disk, regardless of what else is going on in the system. IOPRIO_CLASS_IDLE means the process will get I/O time when no-one else needs the disk. For further information refer to manuals of ionice command line utility or ioprio_get system call.

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.rlimit(). See man prlimit for futher information.

Availability: Linux

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末鸡岗,一起剝皮案震驚了整個濱河市混槐,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌轩性,老刑警劉巖声登,帶你破解...
    沈念sama閱讀 206,968評論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異揣苏,居然都是意外死亡捌刮,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,601評論 2 382
  • 文/潘曉璐 我一進店門舒岸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來绅作,“玉大人,你說我怎么就攤上這事蛾派《砣希” “怎么了?”我有些...
    開封第一講書人閱讀 153,220評論 0 344
  • 文/不壞的土叔 我叫張陵洪乍,是天一觀的道長眯杏。 經(jīng)常有香客問我,道長壳澳,這世上最難降的妖魔是什么岂贩? 我笑而不...
    開封第一講書人閱讀 55,416評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮巷波,結(jié)果婚禮上萎津,老公的妹妹穿的比我還像新娘。我一直安慰自己抹镊,他們只是感情好锉屈,可當我...
    茶點故事閱讀 64,425評論 5 374
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著垮耳,像睡著了一般颈渊。 火紅的嫁衣襯著肌膚如雪遂黍。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,144評論 1 285
  • 那天俊嗽,我揣著相機與錄音雾家,去河邊找鬼。 笑死绍豁,一個胖子當著我的面吹牛榜贴,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播妹田,決...
    沈念sama閱讀 38,432評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼鹃共!你這毒婦竟也來了鬼佣?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,088評論 0 261
  • 序言:老撾萬榮一對情侶失蹤霜浴,失蹤者是張志新(化名)和其女友劉穎晶衷,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體阴孟,經(jīng)...
    沈念sama閱讀 43,586評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡晌纫,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,028評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了永丝。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片锹漱。...
    茶點故事閱讀 38,137評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖慕嚷,靈堂內(nèi)的尸體忽然破棺而出哥牍,到底是詐尸還是另有隱情,我是刑警寧澤喝检,帶...
    沈念sama閱讀 33,783評論 4 324
  • 正文 年R本政府宣布嗅辣,位于F島的核電站,受9級特大地震影響挠说,放射性物質(zhì)發(fā)生泄漏澡谭。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,343評論 3 307
  • 文/蒙蒙 一损俭、第九天 我趴在偏房一處隱蔽的房頂上張望蛙奖。 院中可真熱鬧,春花似錦杆兵、人聲如沸外永。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,333評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽伯顶。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間祭衩,已是汗流浹背灶体。 一陣腳步聲響...
    開封第一講書人閱讀 31,559評論 1 262
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留掐暮,地道東北人蝎抽。 一個月前我還...
    沈念sama閱讀 45,595評論 2 355
  • 正文 我出身青樓,卻偏偏與公主長得像路克,于是被迫代替她去往敵國和親樟结。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 42,901評論 2 345

推薦閱讀更多精彩內(nèi)容

  • 最近嘗試不同色彩加入禪繞畫
    吾線布谷鳥閱讀 632評論 0 1
  • 要警惕那些帶有勸說性的愛精算,他們都是騙人的瓢宦。我才不要你過那種權(quán)且“正確”的生活,你去冒險吧灰羽,去快樂驮履,去仗劍天涯,去聽...
    ShAbbbyTY閱讀 389評論 0 0
  • 3廉嚼、跟一個同事聊天玫镐,最近有什么好事發(fā)生呀?結(jié)果他說了好多不好的事情怠噪,我問恐似,這種事情其它的店有沒有?即使發(fā)生了傍念,我們...
    Martin_馬丁閱讀 62評論 0 0