Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26193404
  • 博文数量: 2065
  • 博客积分: 10377
  • 博客等级: 上将
  • 技术积分: 21525
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-04 17:50
文章分类

全部博文(2065)

文章存档

2012年(2)

2011年(19)

2010年(1160)

2009年(969)

2008年(153)

分类: Python/Ruby

2009-04-29 13:36:34

sys模块

sys模块包含系统对应的功能。我们已经学习了sys.argv列表,它包含命令行参数。

#!/usr/bin/python
# Filename: cat.py


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, # notice comma
    f.close()

# Script starts from here
if len(sys.argv) < 2:
    print 'No action specified.'
    sys.exit()

if sys.argv[1].startswith('--'):
    option = sys.argv[1][2:]
    # fetch sys.argv[1] but without the first two characters
    if option == 'version':
        print 'Version 1.2'
    elif option == 'help':
        print '''\
This program prints files 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.'
    sys.exit()
else:
    for filename in sys.argv[1:]:
        readfile(filename)

(源文件:)

输出

$ python cat.py
No action specified.

$ python cat.py --help
This program prints files to the standard output.
Any number of files can be specified.
Options include:
  --version : Prints the version number
  --help    : Display this help

$ python cat.py --version
Version 1.2

$ python cat.py --nonsense
Unknown option.

$ python cat.py poem.txt
Programming is fun
When the work is done
if you wanna make your work also fun:
        use Python!

它如何工作

这个程序用来模范Linux/Unix用户熟悉的cat命令。你只需要指明某些文本文件的名字,这个程序会把它们打印输出。

在Python程序运行的时候,即不是在交互模式下,在sys.argv列表中总是至少有一个项目。它就是当前运行的程序名称,作为sys.argv[0](由于Python从0开始计数)。其他的命令行参数在这个项目之后。

为了使这个程序对用户更加友好,我们提供了一些用户可以指定的选项来了解更多程序的内容。我们使用第一个参数来检验我们的程序是否被指定了选项。如果使用了--version选项,程序的版本号将被打印出来。类似地,如果指定了--help选项,我们提供一些关于程序的解释。我们使用sys.exit函数退出正在运行的程序。和以往一样,你可以看一下help(sys.exit)来了解更多详情。

如果没有指定任何选项,而是为程序提供文件名的话,它就简单地打印出每个文件地每一行,按照命令行中的顺序一个文件接着一个文件地打印。

顺便说一下,名称catconcatenate 的缩写,它基本上表明了程序的功能——它可以在输出打印一个文件或者把两个或两个以上文件连接/级连在一起打印。

sys.version字符串给你提供安装的Python的版本信息。sys.version_info元组则提供一个更简单的方法来使你的程序具备Python版本要求功能。

[swaroop@localhost code]$ python
>>> import sys
>>> sys.version
'2.3.4 (#1, Oct 26 2004, 16:42:40) \n[GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)]'
>>> sys.version_info
(2, 3, 4, 'final', 0)

对于有经验的程序员,sys模块中其他令人感兴趣的项目有sys.stdinsys.stdoutsys.stderr它们分别对应你的程序的标准输入、标准输出和标准错误流。


补充:

1、print 'Hello World!'  ----使用标准的输入输出流的实现方法

import sys

sys.stdout.write('Hello World!')  -- python中的标准输出实现

2、print 'Hi, %s!' % raw_input('Please enter your name:')

以上是让用户从控制台中输入信息即 标准的输入操作!

import sys

print 'Please enter your name:',
name=sys.stdin.readline()[:-1]   ----标准输入操作流
print 'Hi, %s!' % name

进一步:

Python程序内部将stdin,stdout,stderr读写操作重定向到一个内部对象。借助StringIO模块实现!

from StringIO import StringIO
import sys
buff =StringIO()

temp = sys.stdout          #标准输出存放到一个StringIO对象                          
sys.stdout = buff                                    
print 42, 'hello', 0.001   #不会打印出来因为在程序内部将其重定向到了stdout对象了

sys.stdout =temp           #恢复过来                 
print buff.getvalue()      #直接从内部对象中提取数据




阅读(1535) | 评论(0) | 转发(0) |
0

上一篇:Python-字典常用方法

下一篇:os模块

给主人留下些什么吧!~~