赞
踩
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能够更加友好的输出信息.
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。