Home  >  Article  >  Backend Development  >  Python sys.argv用法实例

Python sys.argv用法实例

WBOY
WBOYOriginal
2016-06-10 15:11:161212browse

sys.argv变量是一个字符串的列表。特别地,sys.argv包含了命令行参数 的列表,即使用命令行传递给你的程序的参数。

这里,当我们执行python using_sys.py we are arguments的时候,我们使用python命令运行using_sys.py模块,后面跟着的内容被作为参数传递给程序。Python为我们把它存储在sys.argv变量中。记住,脚本的名称总是sys.argv列表的第一个参数。所以,在这里,'using_sys.py'是sys.argv[0]、'we'是sys.argv[1]、'are'是sys.argv[2]以及'arguments'是sys.argv[3]。注意,Python从0开始计数,而非从1开始。

sys.argv[]是用来获取命令行参数的,sys.argv[0]表示代码本身文件路径;比如在CMD命令行输入 “python  test.py -help”,那么sys.argv[0]就代表“test.py”。

sys.startswith() 是用来判断一个对象是以什么开头的,比如在python命令行输入“'abc'.startswith('ab')”就会返回True
以下实例参考:

复制代码 代码如下:

#!/usr/local/bin/env python
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()
print "sys.argv[0]---------",sys.argv[0]                                   
print "sys.argv[1]---------",sys.argv[1]                                   
print "sys.argv[2]---------",sys.argv[2]
# Script starts from here
if len(sys.argv)     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 test.py --version help

复制代码 代码如下:

sys.argv[0]--------- test.py
sys.argv[1]--------- --version
sys.argv[2]--------- help
Version 1.2

注意:sys.argv[1][2:]表示从第二个参数,从第三个字符开始截取到最后结尾,本例结果为:version
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn