python sys.argv[]

 

sys.argv[]是用来获取命令行参数的,是一个由该脚本自身路径和其它输入的参数组成的List。sys.argv[0]表示代码本身文件路径。

这里,当我们执行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开始。

 

# -*- coding:utf-8 -*-

from sys import argv

script,first,second,third=argv

print "The script is called:",script
print "Your first variable is:", first
print "Your second variable is:",second
print "Your third variable is:",third

> python ex13.py first,2nd,3th
The script is called: ex13.py
Your first variable is: first
Your second variable is: 2nd
Your third variable is: 3th

 

# -*- coding:utf-8 -*-

import sys

def readfile(filename):
    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 specofied."
    sys.exit()
    
for i in range(len(sys.argv)):
    print "sys.argv[%d]-----%s" %(i,sys.argv[i])


if sys.argv[1].startswith('--'):
    option=sys.argv[1][2:]
    #fetch sys.argv[1] without the first two characters
    if option == "version":
        print "Version 1.2"
    if 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
           
           ex13_2.py filename : will display content in file 
           """
        
    if option not in ["version","help"]:
        print "Unknow option."
        sys.exit()
else:
    for filename in sys.argv[1:]:
        readfile(filename)


> python ex13_3.py
No action specofied.
> python ex13_3.py --version
sys.argv[0]-----ex13_3.py
sys.argv[1]-------version
Version 1.2
> python ex13_3.py --help
sys.argv[0]-----ex13_3.py
sys.argv[1]-------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

                   ex13_2.py filename : will display content in file

> python ex13_3.py 1.txt 2.txt
sys.argv[0]-----ex13_3.py
sys.argv[1]-----1.txt
sys.argv[2]-----2.txt
test for sys.argv
test2
> python ex13_3.py 1.txt
sys.argv[0]-----ex13_3.py
sys.argv[1]-----1.txt
test for sys.argv
> python ex13_3.py 1.txt 2.txt
sys.argv[0]-----ex13_3.py
sys.argv[1]-----1.txt
sys.argv[2]-----2.txt
test for sys.argv
test2
> python ex13_3.py 1.txt 2.txt 3.txt
sys.argv[0]-----ex13_3.py
sys.argv[1]-----1.txt
sys.argv[2]-----2.txt
sys.argv[3]-----3.txt
test for sys.argv
test2
test3

 

posted on 2016-12-15 17:16  大大的橙子  阅读(2107)  评论(0编辑  收藏  举报

导航