Ref :深入 Python :Dive Into Python 中文版 中处理命令行参数一节http://www.woodpecker.org.cn/diveintopython/scripts_and_streams/command_line_arguments.html
以下源码为的《可爱的Python》中 CDay-3中第一道习题,
要点在于对命令行参数的读取和判断
源代码
1 # coding=utf-8
2 '''Lovely Python -3 PyDay
3 PyCDC v0.3
4 @see:http://www.woodpecker.org.cn/diveintopython/scripts_and_streams/command_line_arguments.html
5 '''
6 import os,sys
7 import getopt #导入getopt模块
8
9 CDROM = '/media/cdrom0'
10 def cdWalker(cdrom,cdcfile):
11 export = ""
12 for root, dirs, files in os.walk(cdrom):
13 export+="\n %s;%s;%s" % (root,dirs,files) ///这里的+=其实没有用join方法的效率高
14 open(cdcfile, 'w').write(export) ///open加上'w'有新建的效果
15
16 def usage():
17 print '''PyCDC 使用方式:
18 python cdays-3-exercise-1.py -d cdc -k 中国火
19 #搜索 cdc 目录中的光盘信息,寻找有“中国火”字样的文件或是目录,在哪张光盘中
20 '''
21 try:
22 opts, args = getopt.getopt(sys.argv[1:], 'hd:e:k:') ///只有h后不加:,因为其后没其他参数
23 except getopt.GetoptError:
24 usage()
25 sys.exit()
26
27 if len(opts) == 0:
28 usage()
29 sys.exit()
30
31 c_path = ''
32 for opt, arg in opts: ///arg由这个opts中读取出来,不明白上面的args有什么用处
33 if opt in ('-h', '--help'):
34 usage()
35 sys.exit()
36 elif opt == '-e':
37 #判别sys.argv[2]中是否有目录,以便进行自动创建
38 #cdWalker(CDROM, arg)
39 print "记录光盘信息到 %s" % arg
40 elif opt == '-d':
41 c_path = arg
42 elif opt == '-k':
43 if not c_path: ///当c_path为'',即未被赋值时会进入下面的命令
44 usage()
45 sys.exit()
46 #进行文件搜索
*需要注意处用黄色高亮标注