zoukankan      html  css  js  c++  java
  • sys模块的初步认识

     1  #!/usr/bin/python
     2 # Filename: cat.py
     3 
     4 import sys
     5 
     6 def readfile(filename):
     7     '''Print a file to the standard output.'''
     8     f = file(filename)
     9     while True:
    10         line = f.readline()
    11         if len(line) == 0:
    12             break
    13         print line, # notice comma
    14     f.close()
    15 
    16 # Script starts from here
    17 if len(sys.argv) < 2:
    18     print 'No action specified.'
    19     sys.exit()
    20 
    21 if sys.argv[1].startswith('--'):
    22     option = sys.argv[1][2:]
    23     # fetch sys.argv[1] but without the first two characters
    24     if option == 'version':
    25         print 'Version 1.2'
    26     elif option == 'help':
    27         print '''
    28 This program prints files to the standard output.
    29 Any number of files can be specified.
    30 Options include:
    31   --version : Prints the version number
    32   --help    : Display this help'''
    33     else:
    34         print 'Unknown option.'
    35     sys.exit()
    36 else:
    37     for filename in sys.argv[1:]:
    38         readfile(filename) 
    View Code

     这个程序用来模仿linux中的cat命令。

    在python程序运行的时候,即不是在交互模式下,在sys.argv[]列表中总是至少有一个项目,它就是当前运行的程序的名称,其他的命令行参数在这个项目之后。

    另外,sys模块中还有其他特别有用的项目,sys.stdin sys.stdout sys.stderr分别对应标准输入、标准输出、标准错误。

  • 相关阅读:
    Linux系统下ZIP文件解压和压缩命令
    解析XML文件
    数组和集合之间的转换
    数据库密码到期修改密码
    Linux系统中启动jar程序
    JSONArray依赖包
    多态性
    接口----interface
    抽象类
    final关键字
  • 原文地址:https://www.cnblogs.com/lit10050528/p/3341339.html
Copyright © 2011-2022 走看看