免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4879 | 回复: 0
打印 上一主题 下一主题

getopt用法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-05-28 21:13 |只看该作者 |倒序浏览

                                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')]
               
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/20294/showart_1946954.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP