commands 模块 与sys模块

commands 模块
通过python 执行Linux系统命令

commands.getstatusoutput(cmd)
用os.popen()执行命令cmd, 然后返回两个元素的元组(status, result),其中 status为int类型,result为string类型

import commands
cmd = 'ls /home/admin'
c = commands.getstatusoutput(cmd)
print(type(c))
status, output = commands.getstatusoutput(cmd)
print(status)
print(output)
print(type(output))




commands.getoutput(cmd)
只返回执行的结果, 忽略返回值.

import commands

a = commands.getoutput('ls')

print(type(a))

print(a)


sys模块
sys.argv                              #命令行参数List,第一个元素是程序本身路径
sys.exit(n)                          #退出程序,正常退出时exit(0)
sys.version                          #获取Python解释程序的版本信息
sys.maxint                            #最大的Int值
sys.path                              #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform                          #返回操作系统平台名称
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1]



1,    通过sys模块获取程序参数
import sys
print('argv[0] = {0}    argv [1] = {1}'.format(sys.argv[0], sys.argv[1]))
执行:python test.py hello
结果:
argv[0] = E:/test/test.py    argv [1] = hello
解释:
和其他语言一样,python的sys模块默认是把第一个参数默认是程序本省,从第二个参数起都是代码后面跟着的参数,通过sys.arg[n]就可以获得传入到程序中的参数。

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

2..1 sys.stdout 与 print
当我们在 Python 中打印对象调用 print obj 时候,事实上是调用了sys.stdout.write(obj+'\n'),print 将你需要的内容打印到了控制台,然后追加了一个换行符,print 会调用 sys.stdout 的 write 方法
以下两行在事实上等价:
import sys
sys.stdout.write('hello'+'\n')
print 'hello'

2.2 sys.stdin 与 raw_input
import sys
a = raw_input('raw_input_name: ')
print(a)
print 'stdin_name: ', #comma to stay in the same line
b = sys.stdin.readline()[:-1] # -1 to discard the '\n' in input stream
print(b)

2.3    从控制台重定向到文件
Import sys
f_handler=open('out.log', 'w')
sys.stdout=f_handler
print 'hello'
在当前文件下新生成一个文件out.log,文件内容为hello,

3,    捕获sys.exit(n)调用
功能:执行到主程序末尾,解释器自动退出,但是如果需要中途退出程序,可以调用sys.exit函数,带有一个可选的整数参数返回给调用它的程序,表示你可以在主程序中捕获对sys.exit的调用。(0是正常退出,其他为异常)
def exitfunc():
    print "hello world"
sys.exitfunc = exitfunc  # 设置捕获时调用的函数
print "aaaaaaaa"
sys.exit(1)    # 退出自动调用exitfunc()后,程序依然退出了
print "there"  # 不会被 print
结果:
aaaaaaaa
hello world
解释:
1,    设置sys.exitfunc函数,及当执行sys.exit(1)的时候,调用exitfunc函数
2,    sys.exit(1)后面的内容就不会执行了,因为程序已经退出。


posted on 2017-11-11 00:38  song-liang  阅读(179)  评论(0编辑  收藏  举报

导航