在python中如何使用sys.argv

来源:互联网 发布:卓智网络怎么样 编辑:程序博客网 时间:2024/05/19 22:06

在python中如何使用sys.argv

sys.argv是什么?
  sys.argv是一个列表,它包含了脚本传递的命令行参数。
  len(sys.argv)得到参数的个数
  sys.argv[0]是脚本的名字
  为了使用sys.argv,要首先import sys模块

例子:

#!/usr/bin/env python#-*- coding:utf-8 -*-import sysprint "This is the name of the script脚本名: ", sys.argv[0]print "Number of arguments: ", len(sys.argv)print "The arguments are: " , sys.argv #列表
运行结果:





例子:代码来自于简明教程

#!/usr/bin/env python#-*- coding:utf-8 -*-# Filename: cat.pyimport sysdef 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 hereif 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)
运行结果:



参考资料:

1、http://woodpecker.org.cn/abyteofpython_cn/chinese/ch14s02.html

2、http://www.pythonforbeginners.com/systems-programming/python-sys-argv/

原创粉丝点击