1.commands模块

linux系统环境下用于支持shell的一个模块


1)getoutput()

  返回值只有返回结果(字符串类型),没办法判断执行结果是否正常


例子

import commands

cmd = "ls /data/temp"

result1 = commands.getoutput(cmd)

print(type(result1))                   # 类型为str

print(result1)


结果:

<type 'str'>

2.py



2)getstatusoutout()

  返回结果是一个tuple元组,第一个值为接收状态码,int类型,0表示正常,非0表示异常;第二个值为字符串,即shell命令执行的结果


例子

import commands

cmd = "ps -ef"

status,result2 = commands.getstatusoutput(cmd)

print(type(status))

print(status)

print(type(result2))

print(result2)


结果:

<type 'int'>

0

<type 'str'>

UID         PID   PPID  C STIME TTY          TIME CMD

root          1      0  0 Oct09 ?        00:00:14 /usr/lib/systemd/systemd --switched-root --system --deserialize 21

root          2      0  0 Oct09 ?        00:00:00 [kthreadd]



2.sys模块

1)通过sys模块获取程序参数

sys.argv[0]:第一个参数,脚本本身

sys.argv[1]:第二个参数,传入的第一个参数


例子

import sys

print("argv[0]={0}   argv[1]={1}".format(sys.argv[0],sys.argv[1]))

结果:

argv[0]=C:/Users/test/PycharmProjects/a/a1.python.py    argv[1]=parameter1



2)sys.stdin、sys.stdout、sys.stderr

  stdin、stdout、stderr 变量包含与标准I/O流对应的流对象。如果需要更好地控制输出,而print 不能满足你的要求,你也可以替换它们,重定向输出和输入到其它设备( device ),或者以非标准的方式处理它们


例子1:sys.stdout与print

import sys

sys.stdout.write("hello"+ "\n")

print("hello")


结果:

hello

hello


例子2:sys.stdin与raw_input

import sys

name1 = raw_input("input your name: ")

print(name1)

print 'stdin_your_name: ',        # command to stay in the same line

name2 = sys.stdin.readline()[:-1]     # -1 to discard the '\n' in input stream

print(name2)


结果:

input your name: huangzp

huangzp

stdin_your_name: huangzp

huangzp



例子3: 控制台重定向文件

import sys

f_hander = open("out.log","w")

sys.stdout = f_hander

print("hello")


结果:

本地生成一个out.log文件,内容为hello



3)捕获sys.exit(n)调用

  执行到主程序末尾,解释器自动退出,但如需中途退出程序,可以调用sys.exit函数,带有一个可选的整数参数返回给调用它的程序,表示你可以在主程序中捕获对sys.exit的调用。(0是正常退出,其他为异常)


例子

import sys

def exitfunc():

   print "hello world"

sys.exitfunc = exitfunc   # 设置捕获时调用的函数

print "start"

sys.exit(1)               # 退出自动调用exitfunc()后,程序退出

print "end"             # 不会执行print


结果:

start

hello world


说明:

  设置sys.exitfunc函数,及当执行sys.exit(1)的时候,调用exitfunc函数;sys.exit(1)后面的内容就不会执行了,因为程序已经退出