您的位置:首页 > 编程语言 > Python开发

Python 学习笔记 (8)—— sys模块

2014-02-11 17:30 351 查看

主要介绍用的比较多的sys的模块命令包括:sys.argv,sys.platform,sys.getdefaultencoding,sys.setdefaultencoding(),sys.getfilesystemencoding(),sys.exit(n),sys.path,sys.modules.keys(),sys.stdin,sys.stdout,sys.stderr 等。

sys.argv    获取参数
参数获取从0开始,而不是1,0为命令本身
#!/usr/bin/python
import sys
print "I the first arg :", sys.argv[1]
print "I the second arg :", sys.argv[2]
print "All of the args are :"
for i in sys.argv:
        print i

执行结果:
[root@node1 python]# python arg.py hello python
I the first arg : hello
I the second arg : python
All of the args are :
arg.py
hello
python

sys.platform   获取当前操作系统平台

具体的返回值如下:
>>> import sys
>>> sys.platform
'linux2'

操作系统 返回值
Linux (2.x and 3.x)
'linux2'
Windows
 'win32' 
Windows/Cygwin
 'cygwin'
Mac OS X
'darwin' 
OS/2
 'os2'
OS/2 EMX
'os2emx' 
RiscOS
'riscos'
AtheOS
'atheos'

 

实例:
根据不同操作系统判断该使用什么命令,例如在在linux 下用“clear”而在windows下用“cls”

#!/usr/bin/python
import sys
ostype = sys.platform
if ostype == "linux" or ostype == "linux2":
        cmd = "clear"
else:
        cmd = "cls"
print "The clear command is :", cmd

[root@node1 python]# python os.py 
The clear command is : clear

sys.exit(n)        设置退出返回值(0表示正常退出,其他非0整数表示不正常,可以通过异常捕获)

 

#!/usr/bin/python
import sys
def exitFunc(value):
        '''Clear function'''
        print value
        sys.exit()

print "hello"

try:
        sys.exit(1)
except SystemExit,value:
        exitFunc(value)
print "Ok"

[root@node1 python]# python esc.py 
hello
1

sys.path      返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
在通过命令"import module_name"时,系统将在以下路径中查找导入的模块,其中第一个为空,表示当前目录
>>> import sys
>>> sys.path
['', '/usr/lib64/python26.zip', '/usr/lib64/python2.6', '/usr/lib64/python2.6/plat-linux2', '/usr/lib64/python2.6/lib-tk', 
'/usr/lib64/python2.6/lib-old', '/usr/lib64/python2.6/lib-dynload', '/usr/lib64/python2.6/site-packages', 
'/usr/lib64/python2.6/site-packages/gtk-2.0', '/usr/lib/python2.6/site-packages']

 

sys.modules.keys()    使用sys模块查找已导入的模块
>>> import sys
>>> print sys.modules.keys()
['copy_reg', 'encodings', 'site', '__builtin__', '__main__', 'encodings.encodings', 'abc', 'posixpath', 
'errno', 'encodings.codecs', '_abcoll', 'types', '_codecs', '_warnings', 'genericpath', 'stat', 'zipimport',
 'encodings.__builtin__', 'warnings', 'UserDict', 'encodings.utf_8', 'sys', 'codecs', 'readline', 'os.path',
 'signal', 'linecache', 'posix', 'encodings.aliases', 'exceptions', 'os']

sys.getdefaultencoding()    获取系统当前编码,一般默认为ascii。


>>> import sys
>>> sys.getdefaultencoding()
'ascii'

sys.setdefaultencoding()    设置系统默认编码


执行dir(sys)时不会看到这个方法,在解释器中执行不通过,可以先执行reload(sys),再执行 setdefaultencoding('utf8'),此时将系统默认编码设置为utf8。
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding('utf8')

 

sys.getfilesystemencoding()    获取文件系统使用编码方式
>>> sys.getfilesystemencoding()
'UTF-8'

 

sys.stdin,sys.stdout,sys.stderr
标准输入和标准错误 (通常缩写为 stdout 和 stderr) 是内建在每一个 UNIX 系统中的管道。 
当你 print 某些东西时,结果前往 stdout 管道;
当你的程序崩溃并打印出调试信息 (例如 Python 中的 traceback (错误跟踪)) 的时候,信息前往 stderr 管道 
stdout 是一个类文件对象;调用它的 write 函数可以打印出你给定的任何字符串。
实际上,这就是 print 函数真正做的事情;它在你打印的字符串后面加上一个硬回车,然后调用 sys.stdout.write 函数。

>>> for i in range(3):
...     print'Dive in'

Dive in
Dive in
Dive in
>>> import sys
>>> for i in range(3):
...     sys.stdout.write('Dive in')

Dive inDive inDive in
>>> for i in range(3):
...     sys.stderr.write('Dive in')

Dive inDive inDive in


在最简单的例子中,stdout 和 stderr 把它们的输出发送到相同的地方
和 stdout 一样,stderr 并不为你添加硬回车;如果需要,要自己加上。
stdout 和 stderr 都是类文件对象,但是它们都是只写的。
它们都没有 read 方法,只有 write 方法。然而,它们仍然是类文件对象,因此你可以将其它任何 (类) 文件对象赋值给它们来重定向其输出。

 

使用sys重定向输出
print 'Dive in'                 # 标准输出
saveout = sys.stdout            # 在重定向前保存stdout,这样的话之后你还可以将其设回正常
fsock = open('out.log', 'w')    # 打开一个新文件用于写入。如果文件不存在,将会被创建。如果文件存在,将被覆盖。
sys.stdout = fsock              # 所有后续的输出都会被重定向到刚才打开的新文件上。

print  'This message will be logged instead of displayed'    # 这样只会将输出结果“打印”到日志文件中;屏幕上不会看到输出
sys.stdout = saveout            # 在我们将 stdout 搞乱之前,让我们把它设回原来的方式。     
fsock.close()                   # 关闭日志文件。

重定向错误信息
fsock = open('error.log', 'w')                   # 打开你要存储调试信息的日志文件。 
sys.stderr = fsock                               # 将新打开的日志文件的文件对象赋值给stderr以重定向标准错误。
raise Exception, 'this error will be logged'     # 引发一个异常,没有在屏幕上打印出任何东西,所有正常的跟踪信息已经写进error.log

 

还要注意你既没有显式关闭日志文件,也没有将 stderr 设回最初的值。
这样挺好,因为一旦程序崩溃 (由于引发的异常),Python 将替我们清理并关闭文件打印到 stderr
向标准错误写入错误信息是很常见的,所以有一种较快的语法可以立刻导出信息

>>> print 'entering function'
entering function
>>> import sys
>>> print >> sys.stderr, 'entering function'

entering function 
print 语句的快捷语法可以用于写入任何打开的文件 (或者是类文件对象)。 
在这里,你可以将单个print语句重定向到stderr而且不用影响后面的print语句。

 

简明教程中的实例
import sys
def readfile(filename):
        '''Print a file to the standard output.'''
        f = file(filename)
        while True:
                line = f.readline()
                if len(line) == 0:
                        break
                print line,
        f.close()
if len(sys.argv) < 2:
        print 'No action specified.'
        sys.exit()
if sys.argv[1].startswith('--'):
        option = sys.argv[1][2:]
        if option == 'version':
                print "Version 1.2"
        elif option == 'help':
                print '''\
This program prints file to the standard output.
Any number of files can be specified.
Options include:
        --version : Prints the version number
        --help    : Display this help'''
        else:
                print 'Unknown option.'
else:
        for filename in sys.argv[1:]:
                readfile(filename)

 

执行结果:
[root@node1 python]# python cat.py 
No action specified.

[root@node1 python]# python cat.py --help
This program prints file to the standard output.
Any number of files can be specified.
Options include:
    --version : Prints the version number
    --help    : Display this help

 

[root@node1 python]# python cat.py --version
Version 1.2

 

[root@node1 python]# python cat.py --t
Unknown option.

 

[root@node1 python]# python cat.py /tmp/test.txt 
hello girl!
hello boy!
hello man!

 

工作原理:
定义readfile 函数逐行读取文件,执行脚本后,判断参数。
若参数长度小于2(命令本身占一个长度,也就是说,命令+参数),输出No action specified.
若参数是以“--”开头(通过sys.startswith 获取开头),则从该参数的第3个字符起截取,比如--help,得到的就是help
若取得的值为"help" 则显示帮助信息,若取得的值为"version",则显示版本信息
若没有匹配到任何选项,则显示“Unknown option”
若直接加文件名,则打印出文件内容

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: