接續(xù)上篇《python 常用內(nèi)建模塊之psutil》安裝psutil,并且獲取一些基本信息,本篇介紹通過psutil獲取到所有進(jìn)程的詳細(xì)信息:
print psutil.pids()
運(yùn)行結(jié)果:
[3865, 3864, 3863, 3856, 3855, 3853, 3776, ..., 45, 44, 1, 0]
p = psutil.Process(1689) # 進(jìn)程名稱 print p.name()
運(yùn)行結(jié)果:
pycharm
p = psutil.Process(1689) print p.exe()
運(yùn)行結(jié)果:
/Applications/PyCharm.app/Contents/MacOS/pycharm
p = psutil.Process(1689) print p.cwd()
運(yùn)行結(jié)果:
/Applications/PyCharm.app/Contents/bin
p = psutil.Process(1689) print p.cmdline()
運(yùn)行結(jié)果:
['/Applications/PyCharm.app/Contents/MacOS/pycharm']
p = psutil.Process(1689) print p.ppid()
運(yùn)行結(jié)果:
1
p = psutil.Process(1689) print p.parent()
運(yùn)行結(jié)果:
psutil.Process(pid=1, name='lound', started='2018-08-12 09:13:10')
p = psutil.Process(1689) print p.children()
運(yùn)行結(jié)果:
[psutil.Process(pid=30566, name='Python', started='14:52:04'), psutil.Process(pid=1755, name='fsnotifier', started='2018-08-12 12:17:23')]
p = psutil.Process(1689) print p.status()
運(yùn)行結(jié)果:
running
p = psutil.Process(1689) print p.username()
運(yùn)行結(jié)果:
fby
p = psutil.Process(1689) print p.create_time()
運(yùn)行結(jié)果:
1565583434.66
p = psutil.Process(1689) print p.terminal()
運(yùn)行結(jié)果:
/dev/ttys002
p = psutil.Process(1689) print p.cpu_times()
運(yùn)行結(jié)果:
pcputimes(user=5228.817022976, system=2723.374170112, children_user=0.0, children_system=0.0)
p = psutil.Process(1689) print p.memory_info()
運(yùn)行結(jié)果:
pmem(rss=875470848L, vms=10986835968L, pfaults=10496095, pageins=18513)
p = psutil.Process(1689) print p.open_files()
運(yùn)行結(jié)果:
[]
p = psutil.Process(1689) print p.connections()
運(yùn)行結(jié)果:
[]
p = psutil.Process(1689) print p.num_threads()
運(yùn)行結(jié)果:
1
p = psutil.Process(1689) print p.threads()
運(yùn)行結(jié)果:
[pthread(id=1, user_time=0.090318, system_time=0.062736)]
p = psutil.Process(1689) print p.environ()
運(yùn)行結(jié)果:
{'SHELL': '/bin/bash', 'PATH': '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:...', 'PWD': '/Users/michael', 'LANG': 'zh_CN.UTF-8', ...}
p = psutil.Process(1689) p.terminate()
運(yùn)行結(jié)果:
Terminated: 15 <-- 自己把自己結(jié)束了
和獲取網(wǎng)絡(luò)連接類似,獲取一個(gè)root用戶的進(jìn)程需要root權(quán)限,啟動(dòng)Python交互環(huán)境或者.py文件時(shí),需要sudo權(quán)限。
psutil還提供了一個(gè)test()函數(shù),可以模擬出ps命令的效果:
import psutil psutil.test()
運(yùn)行結(jié)果:
USER PID %MEM VSZ RSS TTY START TIME COMMAND root 0 24.0 74270628 2016380 ? Nov18 40:51 kernel_task root 1 0.1 2494140 9484 ? Nov18 01:39 launchd root 44 0.4 2519872 36404 ? Nov18 02:02 UserEventAgent root 45 ? 2474032 1516 ? Nov18 00:14 syslogd root 47 0.1 2504768 8912 ? Nov18 00:03 kextd root 48 0.1 2505544 4720 ? Nov18 00:19 fseventsd _appleeven 52 0.1 2499748 5024 ? Nov18 00:00 appleeventsd root 53 0.1 2500592 6132 ? Nov18 00:02 configd ...
聯(lián)系客服