- 论坛徽章:
- 0
|
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 |
|