系统进程管理方法

(1)进程信息

>>> psutil.pids()    #列出所用进程ID

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 37, 38, 40, 41, 71, 205, 207, 244, 245, 246, 353, 354, 442, 445, 657, 1093, 1127, 1128, 1129, 1130, 1170, 1594, 1631, 1737, 1744, 1791, 1806, 1824, 1833, 1834, 1835, 1837, 1838, 1839, 1840, 1841, 1842, 1845, 1857, 1899, 1903, 1917, 1926, 1927, 1969, 1971, 1975, 2000, 2016, 2032, 2044, 2052, 2063, 2071, 2097, 2105, 2116, 2117, 2118, 2119, 2120, 2121, 2122, 2123, 2136, 2185, 2198, 2210, 2211, 2231, 2285, 2290, 2292, 2294, 2296, 2298, 2314, 2316, 2331, 2401, 2402, 2403, 2406, 2410, 2428, 2429, 2431, 2439, 2440, 2442, 2443, 2444, 2445, 2447, 2456, 2458, 2464, 2487, 2489, 2490, 2514, 2516, 2553, 2565, 2568]

>>> p=psutil.Process(2456)    #实例化一个process对象,参数为一进程PID

>>> p.name()                  #获取进程名称

'pulseaudio'

>>> p.exe()                    #进程bin路径

'/usr/bin/pulseaudio'

>>> p.cwd()                    #进程工作目录绝对路径

'/'

>>> p.status()                #进程状态

'sleeping'

>>> p.create_time()            #进程创建时间

1441249488.7

>>> p.uids()                    #进程UID信息

puids(real=42, effective=42, saved=42)

>>> p.cpu_times()                #进程CPU时间信息

pcputimes(user=0.070000000000000007, system=0.47999999999999998)

>>> p.memory_percent()            #进程的内存利用率

0.13787605954895574

>>> p.memory_info()                #进程内存的RSS、VMS

pmem(rss=4349952, vms=437780480)

>>> p.io_counters()                #进程IO信息,包括读写IO数及字节数

pio(read_count=652, write_count=33, read_bytes=77824, write_bytes=20480)

>>> p.connections()                #返回打开进程SOCKET的namedutples列表

[]

>>> p.num_threads()                #进程开启的线程数

3

(2)popen类的使用

用于获取用户启动的应用程序进程信息,以便跟踪程序进程的运行状态。

>>> import psutil

>>> from subprocess import PIPE

>>> p=psutil.Popen(["/usr/bin/python","-c","print('hello')"],stdout=PIPE)

>>> p.name()

'python'

>>> p.username()

'root'

>>> p.communicate()

('hello\n', None)