python编写工具之基础——处理命令行参数
2016-03-18 23:51
573 查看
1.分类
1.命令行的参数的位置是固定的。比如ip是第一个参数,端口是第二个,而不能反过来2.位置不固定。用一横杠加个字母什么的,表示他后面跟的是什么参数(如 -p 8888 :代表端口是8888)
2.如何获得命令行参数
必须导入sys模块~import sys print sys.argv
可以看到 sys.argv是一个列表,获得的参数中,第一个文件名,后面才是我们输入的各种参数
3.参数的位置是固定的
# encoding: utf-8 """ @version: @author: giantbranch @file: fix_position.py @time: 2016/3/18 21:58 """ import sys # print sys.argv def test1(): print "你调用了test1" def getYourWord(word): print "你输入了" + word def main(): try: # 获取第二个命令行参数,因为第一个为文件名 func = sys.argv[1] # 通过判断调用相应功能 if(func == "test1"): test1() elif(func == "say"): try: getYourWord(sys.argv[2]) except: print "请输入你想say什么" else: print "输入参数只能使test1或say" except: print "请输入一个参数,只能使test1或say" main()
3.参数的位置是不固定的
#-*- coding:utf8 -*- """ @version: @author: giantbranch @file: unfix_position.py @time: 2016/3/18 22:57 """ import sys import getopt def test1(): print "你调用了test1" def getYourWord(word): print "你输入了" + word def usage(): print "用法举例:" print "python unfix_position.py -h" print "python unfix_position.py --help" print "python unfix_position.py -t" print "python unfix_position.py --test1" print "python unfix_position.py -s hello" # 这个不行 print "python unfix_position.py --say hello" def main(): # 读取命令行选项,若没有该选项则显示用法 try: # opts:一个列表,列表的每个元素为键值对 # args:其实就是sys.argv[1:] # sys.argv[1:]:只处理第二个及以后的参数 # "ts:h":选项的简写,有冒号的表示后面必须接这个选项的值(如 -s hello) # ["help", "test1", "say"] :当然也可以详细地写出来,不过要两条横杠(--) opts, args = getopt.getopt(sys.argv[1:], "ts:h",["help", "test1", "say"]) # print opts # 具体处理命令行参数 for o,v in opts: if o in ("-h","--help"): usage() elif o in ("-t", "--test1"): test1() # 经测试--是不能带后继值的 elif o in ("-s", "--say"): getYourWord(v) except getopt.GetoptError as err: # print str(err) usage() main()
好了,就到这,具体写工具就自我发挥咯
相关文章推荐
- 发布你的Python模块
- Python爬虫实现半自动发微博
- python标准库学习4-time
- 初学者必知的Python中优雅的用法
- 在Ubuntu 14.04中升级python到2.7.11
- mysql-connector-python, mysql-connector-python-rf and mysql-connector-repackaged
- 粒子群算法实现之python
- pip install mysql-connector-python安装时报错不满足requirement
- (3)中文分词——Python结巴分词器
- (9)Python爬虫——下载PDF
- 《跟着小吴哥学python》之 02 python搭建开发环境
- Python中特殊函数和表达式 filter,map,reduce,lambda
- Learning Python(16)--多线程编程(threading,Queue模块)
- python 汉诺塔问题(Tower of Hanoi Puzzle)
- xgboost[python版本]的安装
- python标准库学习3-fileinput
- Vim 的 Python 编辑器详细配置过程 (Based on Ubuntu 12.04 LTS)
- python-for循环
- python流程控制
- python数据类型--字典