【python运维】系统进程管理方法

1、进程信息管理

获取所有进程的PID
>>> pids()
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 15, 16, 17, 178, 179, 182, 184, 252, 253, 254, 255, 256, 473, 517, 518, 522, 523, 524, 531, 544, 568, 594, 627, 1650, 2189, 2190, 2191, 2217, 2683, 3031, 3426, 3471, 3473, 3495, 3498, 3508, 3519, 3546, 3547, 3554, 3578, 3593, 3662, 3672, 3685, 3686, 3694, 3702, 3712, 3749, 3774, 3779, 3792, 3801, 3815, 3877, 3933, 3955, 3963, 3982, 3996, 4077, 4094, 4124, 4125, 4196, 4202, 4204, 4206, 4207, 4208, 4216, 4217, 4315, 4317, 4318, 4342, 4344, 4358, 4391, 4398, 4431, 4432, 4438, 4439, 4443, 4445, 4466, 4467, 4469, 4471, 4475, 4477, 4481, 4483, 4485, 4489, 4497, 4524, 4533, 4535, 4537, 4540, 4541, 4547, 4549, 4552, 4558, 4573, 4593, 4599, 4600, 4601, 4638, 4640, 4642, 4657, 4731, 4752, 4769, 5316, 5429, 5535, 5537, 5539, 14908]
获取单个进程的信息(以PID为5537为例)
>>> p = Process(5537)
>>> p
<psutil.Process(pid=5537, name='sh') at -1209176468>
>>> p.name()
'sh'
>>> p.exe() //获取进程的bin路径
'/bin/bash'
>>> p.cwd() //获取进程工作的绝对路径
'/root'
>>> p.status() //进程状态
'sleeping'
>>> p.create_time() //进程创建时间,以时间戳形式显示
1512435331.8699999
>>> p.uid / p.gid //分别获取进程uid和gid信息
>>> p.cpu_affinity() //获取进程cpu亲和度
[0, 1]
>>> p.memory_percent() //进程内存利用率
0.025554286948605991
>>> p.memory_info() //获取进程内存rss、vms信息
pmem(rss=10625024, vms=29462528)
RSS : "Resident Set Size", 实际驻留"在内存中"的内存数. 不包括已经交换出去的代码. 举一个例子: 如果你有一个程序使用了100K内存, 操作系统交换出40K内存, 那么RSS为60K. RSS还包括了与其它进程共享的内存区域. 这些区域通常用于libc库等.
RSS只有在进程使用CPU时才更新,如果进程idle了,就再也不会更新,永远是那么大。
RSS = sum of private region pages  +
       (sum of shared region pages /
       number of references)                                         
The number of references is a count of the number of attachments to the memory region.  attachments, for shared regions, may come from several processes sharing the same memory, a single process with multiple attachments, or combinations of these. This value is only updated when a process uses CPU.Thus, under memory pressure, this value may be higher than the actual amount of resident memory for processes which are idle because their memory pages
may no longer be resident or the reference count for shared segments may have changed.

>>> p.io_counters() //获取进程IO信息,包括读写IO数及字节数
pio(read_count=633, write_count=1083, read_bytes=0, write_bytes=0)
>>> p.num_threads() //获取进程开启的进程数
1

2、popen类的使用

poepn类可以获取用户启动的应用程序进程信息,以跟踪程序的运行状态
>>> from psutil import *
>>> from subprocess import PIPE //利用管道标准输出
>>> p = Popen(["/usr/bin/python", "-c", "print('hello')"], stdout=PIPE)
//将p进行实例化,然后就可以获取这个进程的各种信息
如:
>>> p.name()
'python'

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值