Python之sys模块小探

Sys模块函数之多,我只能选取本身认为比较实用的一些函数列在此处。借马云找员工的说法,”找最合适的而不是最天才的,这句话,我我的以为在不少方面都能适应,学习也不在话下。Sys模块功能的确不少,但咱们应该将重点放在那些功能才是最适合咱们的,为此,我列的这些函数,就是我认为比较适合我之后开发的函数。html

(1)sys.argvpython

不少人会想,我如何给个人程序在外部传递参数呢?这个,就能够实现。如:linux

Tesy.pyshell

Import sys小程序

Print sys.argv[number]windows

通常状况下,number0是这个脚本的名字,12…则为命令行下传递的参数.如:app

Test.py脚本内容:ide

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 SystemExitexception, 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.stderrand 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.exitpython程序中退出,将会产生一个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, stderrPython中无非都是文件属性的对象,他们在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()


若是想了解更多,请关注咱们的公众号
公众号ID:opdevos
扫码关注

gongzhouhao.jpg

相关文章
相关标签/搜索