接续上篇《python 常用内建模块之psutil》安装psutil,并且获取一些基本信息,本篇介绍通过psutil获取到所有进程的详细信息:
print psutil.pids()
运行结果:
[3865, 3864, 3863, 3856, 3855, 3853, 3776, ..., 45, 44, 1, 0]
p = psutil.Process(1689) # 进程名称 print p.name()
运行结果:
pycharm
p = psutil.Process(1689) print p.exe()
运行结果:
/Applications/PyCharm.app/Contents/MacOS/pycharm
p = psutil.Process(1689) print p.cwd()
运行结果:
/Applications/PyCharm.app/Contents/bin
p = psutil.Process(1689) print p.cmdline()
运行结果:
['/Applications/PyCharm.app/Contents/MacOS/pycharm']
p = psutil.Process(1689) print p.ppid()
运行结果:
1
p = psutil.Process(1689) print p.parent()
运行结果:
psutil.Process(pid=1, name='lound', started='2018-08-12 09:13:10')
p = psutil.Process(1689) print p.children()
运行结果:
[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()
运行结果:
running
p = psutil.Process(1689) print p.username()
运行结果:
fby
p = psutil.Process(1689) print p.create_time()
运行结果:
1565583434.66
p = psutil.Process(1689) print p.terminal()
运行结果:
/dev/ttys002
p = psutil.Process(1689) print p.cpu_times()
运行结果:
pcputimes(user=5228.817022976, system=2723.374170112, children_user=0.0, children_system=0.0)
p = psutil.Process(1689) print p.memory_info()
运行结果:
pmem(rss=875470848L, vms=10986835968L, pfaults=10496095, pageins=18513)
p = psutil.Process(1689) print p.open_files()
运行结果:
[]
p = psutil.Process(1689) print p.connections()
运行结果:
[]
p = psutil.Process(1689) print p.num_threads()
运行结果:
1
p = psutil.Process(1689) print p.threads()
运行结果:
[pthread(id=1, user_time=0.090318, system_time=0.062736)]
p = psutil.Process(1689) print p.environ()
运行结果:
{'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()
运行结果:
Terminated: 15 <-- 自己把自己结束了
和获取网络连接类似,获取一个root用户的进程需要root权限,启动Python交互环境或者.py文件时,需要sudo权限。
psutil还提供了一个test()函数,可以模拟出ps命令的效果:
import psutil psutil.test()
运行结果:
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 ...
联系客服