python sys模块

Sys模块函数之多,我只能选取自己认为比较实用的一些函数列在此处。借马云找员工的说法,”找最合适的而不是最天才的”,这句话,我个人觉得在很多方面都能适应,学习也不在话下。Sys模块功能的确很多,但我们应该将重点放在那些功能才是最适合我们的,为此,我列的这些函数,就是我认为比较适合我以后开发的函数。
(1)sys.argv
很多人会想,我如何给我的程序在外部传递参数呢?这个,就可以实现。如:
Tesy.py
Import sys
Print sys.argv[number]
一般情况下,number为0是这个脚本的名字,1,2…则为命令行下传递的参数.如:
Test.py脚本内容:
import sys
 
print sys.argv[0]
print sys.argv[1]
print sys.argv[2]
print sys.argv[3]
那么
[root@databak scripts]# python test.py arg1 arg2 arg3
test.py
arg1
arg2
arg3
看到,对应的关系了吗?还有,在python.org模块参考手册说,如果在命令行下选用-c那么argv[0]= -c 看下,
[root@databak scripts]# python -c "import sys;print sys.argv[0];print sys.argv[1]" arg1
-c
arg1
如果大家不明白,可以参考下man python
SYNOPSIS
       python [ -d ] [ -E ] [ -h ] [ -i ] [ -m module-name ] [ -O ]
              [ -Q argument ] [ -S ] [ -t ] [ -u ]
              [ -v ] [ -V ] [ -W argument ] [ -x ]
               [ -c command | script | - ] [ arguments ]
(2)sys.platform
大家都知道,当今的程序比较流行的是跨平台。简单的说就是这段程序既可以在 windows 下,换到 linux 下也可以不加修改的运行起来,听起来就不错。所以,这个函数就可以派上用场了。
假设,我们想实现一个清除终端, linux 下用 clear, windows 下用 cls
Ostype=sys.platform()
If ostype==”linux” or ostype==”linux2”:
Cmd=”clear”
Else:
  Cmd=”cls”
(3)  sys.exit(n)
执行至主程序的末尾时,解释器会自动退出. 但是如果需要中途退出程序, 你可以调用sys.exit 函数, 它带有一个可选的整数参数返回给调用它的程序. 这意味着你可以在主程序中捕获对sys.exit 的调用。(注:0是正常退出,其他为不正常,可抛异常事件供捕获!)
import sys
 
def exitfunc(value):
    '''Clear function'''
    print value
    sys.exit(0)
 
print "hello"
 
try:
    sys.exit(1)
except SystemExit,value:
    exitfunc(value)
 
print "come?"
输出结果:
[root@databak scripts]# python test.py
hello
1
以下是python.org库参考手册中,摘抄来的,供参考。
Exit from Python. This is implemented by raising the  SystemExit exception, so cleanup actions specified by finally clauses of  try statements are honored, and it is possible to intercept the exit attempt at an outer level. The optional argument  arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to sys.stderr and results in an exit code of 1. In particular, sys.exit("some  error  message") is a quick way to exit a program when an error occurs.
 
大概意思是说,sys.exit从python程序中退出,将会产生一个systemExit异常,可以为此做些清除除理的工作。这个可选参数默认正常退出状态是0,以数值为参数的范围为:0-127。其他的数值为非正常退出,还有另一种类型,在这里展现的是strings对象类型。
(4)sys.path
大家对模块都有一定了解吧?大家在使用模块的某一个功能前,是不是需要导入呢?答案是需要。那import,__import__命令就不用提干嘛的了吧。那大家在执行import module_name的时候,python内部发生了什么呢?简单的说,就是搜索module_name。根据sys.path的路径来搜索module.name
>>> sys.path
['', '/usr/local/lib/python24.zip', '/usr/local/lib/python2.4', '/usr/local/lib/python2.4/plat-freebsd4', '/usr/local/lib/python2.4/lib-tk', '/usr/local/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages']
大家以后写好的模块就可以放到上面的某一个目录下,便可以正确搜索到了。当然大家也可以添加自己的模块路径。Sys.path.append(“mine module path”).
 
(5)sys.modules
This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks.
Python.org 手册里已经说的很明白了。
For names in sys.modules.keys():
If names != ’sys’:
    ……
(6)sys.stdin,sys.stdout,sys.stderr
stdin , stdout , 以及stderr 变量包含与标准I/O 流对应的流对象. 如果需要更好地控制输出,而print 不能满足你的要求, 它们就是你所需要的. 你也可以替换它们, 这时候你就可以重定向输出和输入到其它设备( device ), 或者以非标准的方式处理它们
从网上摘抄的文章,供大家参考:
#testing stdout

print 'Hello World!'
运行hello.py就会在标准输出的屏幕上打印 Hello World!, 我们再编一个简单的标准输入的小程序 sayhi.py:
#testing stdin

print 'Hi, %s!' % raw_input('Please enter your name:')
当你用键盘输入你的名字后,程序在屏幕上输出Hi,[你的名字]!, 这就是从标准输入:键盘获取信息,再输出到标准输出:屏幕的例子。
那么上面的例子中print 和 raw_input是如何与标准输入/输出流建立关系的呢?
其实Python程序的标准输入/输出/出错流定义在sys 模块中,分别 为: sys.stdin, sys.stdout, sys.stderr
上面的程序分别与下列的程序是一样的:
import sys

sys.stdout.write('Hello World!')
import sys

print 'Please enter your name:',
name=sys.stdin.readline()[:-1]
print 'Hi, %s!' % name

那么sys.stdin, sys.stdout, stderr到底是什么呢?我们在Python运行环境中输入以下代码:
import sys
for f in (sys.stdin, sys.stdout, sys.stderr): print f
输出为:
<open file '<stdin>', mode 'r' at 892210>
<open file '<stdout>', mode 'w' at 892270>
<open file '<stderr>', mode 'w at 8922d0>

由此可以看出stdin, stdout, stderr在Python中无非都是文件属性的对象,他们在Python启动时 自动与Shell 环境中的标准输入,输出,出错关联。
而Python程序的在Shell中的I/O重定向与本文开始时举的DOS命令的重定向完全相同,其实这种重定向是由Shell来提供的,与Python 本身并无关系。那么我们是否可以在Python程序内部将stdin,stdout,stderr读写操作重定向到一个内部对象呢?答案是肯定的。
Python提供了一个StringIO模块来完成这个设想,比如:
from StringIO import StringIO
import sys
buff =StringIO()

temp = sys.stdout                               #保存标准I/O流
sys.stdout = buff                                 #将标准I/O流重定向到buff对象
print 42, 'hello', 0.001

sys.stdout =temp                                 #恢复标准I/O流
print buff.getvalue()
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值