Chinaunix首页 | 论坛 | 博客
  • 博客访问: 575726
  • 博文数量: 43
  • 博客积分: 10257
  • 博客等级: 上将
  • 技术积分: 480
  • 用 户 组: 普通用户
  • 注册时间: 2006-06-06 02:16
文章分类

全部博文(43)

文章存档

2011年(5)

2010年(12)

2009年(6)

2008年(20)

分类: Python/Ruby

2009-05-28 21:13:16

1. getopt的作用是用来解析命令行选项,譬如:

>mysql -u lvdbing -p test -h 192.168.1.20



2. getopt提供的函数包括:

Python 2.6.1+ (r261:67515, Mar 2 2009, 13:11:28)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import getopt
>>> getopt.__all__
['GetoptError', 'error', 'getopt', 'gnu_getopt']
>>>



3. 帮助文档的例子:

>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = s.split()
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'x', [
... 'condition=', 'output-file=', 'testing'])
>>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
>>> args
['a1', 'a2']



4. 一个简单的例子:

lvdbing@lvdbing-desktop:~/Python$ cat mysql.py
#!/usr/bin/env python
# -*- coding=utf-8 -*-

import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "u:p:h:", ["user=","password=","host="])
    except getopt.GetoptError:
        usage()
        sys.exit(1)
    
    print opts
    
def usage():
    print """
python mysql.py -u lvdbing -p test -h 192.168.1.88
-u, --user 登录用户名
-p, --password 登录密码
-h, --host 主机名
"
""


if __name__ == "__main__":
    main()



5. 运行效果:

lvdbing@lvdbing-desktop:~/Python$ python mysql.py -u lvdbing -p test -h 192.168.1.1
[('-u', 'lvdbing'), ('-p', 'test'), ('-h', '192.168.1.1')]

阅读(1263) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~