命令行参数
1. sys.argv[1:]为要处理的参数列表, sys.argv[0]为脚本名, sys.argv[1:]过滤脚本名.
2. “hc:o:”当选项(h)表示开关状态时,后面不带附加参数. 当选项(c:或o:)带附加参数时,选项字符后面加一个”:”号.
3. getopt函数返回两个列表: opts和args. opts是两元组的列表, 选项列表和参数列表.
4. getopt()的第三个参数[, long_options]为可选的长选项参数, 配合短选项使用, 长选项格式如: –image_dir –image_dir=./hello/
代码
import sys
import getopt
def main(argv):
image_dir = '' # 图片文件夹
code_dir = '' # 代码文件夹
out_put = '' # 输出文件
result = list()
try:
opts, args = getopt.getopt(argv, "hi:c:o:", ["image_dir=", "code_dir=", "out_put="])
except getopt.GetoptError:
print 'SearchUnusedImages.py -i <image_dir> -c <code_dir> -o <out_put>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'SearchUnusedImages.py -i <image_dir> -c <code_dir> -o <out_put>'
sys.exit()
elif opt in ("-i", "--image_dir"):
image_dir = arg
elif opt in ("-c", "--code_dir"):
code_dir = arg
elif opt in ("-o", "--out_put"):
out_put = arg
out_file = open(out_put, 'w')
print 'scan start.'
for name, path in search_unused_images(image_dir, code_dir).items():
result.append(path)
for sort_path in sorted(result):
print >> out_file, sort_path
print 'scan over.'
out_file.close()
if __name__ == "__main__":
main(sys.argv[1:])