#!/usr/bin/env python
import sys
print 'prog name is:', sys.argv[0] //sys.argv[0]相当于是bash脚本中的$0
print '#1 is :', sys.argv[1] //其他类推,相当于是bash的$1、$2等
print '#2 is :', sys.argv[2]
++++++++++++++++++++++++++++++++++++++++++++++++
#!/usr/bin/python
import optparse
p = optparse.OptionParser()
p.add_option('--lly','-l',default="lly")
p.add_option('--sysadmin','-s')
options,arguments = p.parse_args() //arguments是输入的参数
print 'Hello ,%s'% options.lly
print 'Hello ,%s'% options.sysadmin
[root@master python]# python opt.py
Hello ,lly
Hello ,None
[root@master python]# python opt.py --lly aa -s ll
Hello ,aa
Hello ,ll
[root@master python]# python opt.py -s ll
Hello ,lly
Hello ,ll
[root@master python]# python opt.py -f ss
Usage: opt.py [options]
opt.py: error: no such option: -f
-v -vv根据级别的不同,输出不同的结果。count计数
#!/usr/bin/python
import sys
import optparse
import os
#def main():
p = optparse.OptionParser(description="python 'ls' command clone ",prog="pyls",version="0.1a",usage="%prog [directory]")
p.add_option("-v",action="count",dest="verbose")
options,arguments = p.parse_args()
if len(arguments) == 1:
if options.verbose:
print "verbose mode enabled at level:%s"% options.verbose
path = arguments[0]
for filename in os.listdir(path):
if options.verbose == 1:
print "filename:%s"% filename
elif options.verbose == 2:
fullpath = os.path.join(path,filename)
print "filename: %s|byte size: %s"%(filename,os.path.getsize(fullpath))
else:
print filename
else:
p.print_help()
#if __name__ == '__main__':
# main()
argparse模块作为optparse的一个替代被添加到Python2.7
http://www.cnblogs.com/lovemyspring/p/3214598.html
#/usr/bin/env python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-s', action='store', dest='simple_value',help='Store a simple value')
parser.add_argument('-c', action='store_const', dest='constant_value',const='value-to-store',help='Store a constant value')
parser.add_argument('-t', action='store_true', default=False,dest='boolean_switch',help='Set a switch to true')
parser.add_argument('-f', action='store_false', default=False,dest='boolean_switch',help='Set a switch to false')
parser.add_argument('-a', action='append', dest='collection',default=[],help='Add repeated values to a list')
parser.add_argument('-A', action='append_const', dest='const_collection',const='value-1-to-append',default=[],help='Add different values to list')
parser.add_argument('-B', action='append_const', dest='const_collection',const='value-2-to-append',help='Add different values to list')
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
results = parser.parse_args()
print 'simple_value =', results.simple_value
print 'constant_value =', results.constant_value
print 'boolean_switch =', results.boolean_switch
print 'collection =', results.collection
print 'const_collection =', results.const_collection