linux 查看python进程_使用Python脚本查看Linux上的进程信息

Zhaoke, 2007-09-06

平台: Python 2.4.4, Fedora Core 6

Python是一门易学, 开源的脚本语言, 下面介绍使用Python脚本查看Linux上的进程信息.

Python模块是Python语言中的一个重要概念,比如commands模块主要封装了命令相应的方法及数据. 我们可以通过import指令导入模块. 下面实例中用到了命令, 系统和字符串模块.

Queryprocess.py的主要功能是查看Linux上指定进程的控制终端(tty), 所有者(uid), 进程号(pid), 父进程号(ppid)和进程开始运行时间(stime).

创建python脚本文件queryprocess.py

islab$ vi queryprocess.py

增加下面源代码到queryproces.py中

#!/usr/bin/env python

# Query process returns the following information: tty, uid, pid, ppid and stime.

import commands, os, string

program = raw_input(”Enter the name of your process to query: “)

try:

#excute the ps command and assign results to a list

utput = commands.getoutput(”ps -ef|grep ” + program)

proginfo = string.split(output)

#display results

print “\n\

Terminal:\t\t”, proginfo[5], “\n\

Owning User:\t\t\t”, proginfo[0], “\n\

Process ID:\t\t”, proginfo[1], “\n\

Parent Process ID:\t”, proginfo[2], “\n\

System Time:\t\t”, proginfo[4]

except:

print “There is a problem with the process u are querying.”

运行querprocess.py

islab$ chmod +x queryprocess.py

islab$ ./queryprocess.py

Enter the name of your process to query: syslogd

Terminal: ?

Owning User: root

Process ID: 2387

Parent Process ID: 1

System Time: Aug09

从上面结果我们看到syslogd进程的所有者是root用户, 进程号为2387, 父进程号是1, 进程开始运行时间是8月9日.

同样我们也可以linux命令行运行下面命令获得上面信息:

islab$ ps -ef|grep syslogd

root 2387 1 0 Aug09 ? 00:00:01 syslogd -m 0

对比两种方法的执行结果后我们可以看到用python能够更加友好的输出信息.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值