command line arguments
wittempj@hotmail.com
martin.witte at gmail.com
Wed Aug 31 14:13:24 EDT 2005
You also could opt for the OptionParser in optparse, it is quiet
powerful, and you can keep your code clean. Your requirements would
translate to something like:
py>#!/usr/bin/env python
py>"""show OptionParser
py>"""
py>from optparse import OptionParser
py>
py>def main():
py> parser = OptionParser(usage = __doc__, version = '3.1415926')
py> parser.add_option("-n", "--name", dest="name", action="store",
py> help="enter a name")
py> parser.add_option("-u", "--url", action="store", dest="url",
help = "enter an url")
py>
py> (options, args) = parser.parse_args()
py> if not options.name and not options.url:
py> parser.error('specify both name and url')
py> print options.name
py> print options.url
py>
py>if __name__ == "__main__":
py> main()
when called it will print things like:
martin at ubuntu:~ $ ./test.py -u www.python.org -n python
{'url': 'www.python.org', 'name': 'python'} []
martin at ubuntu:~ $ ./test.py -u www.python.org -n python
python
www.python.org
martin at ubuntu:~ $ ./test.py -h
usage: show OptionParser
options:
--version show program's version number and exit
-h, --help show this help message and exit
-n NAME, --name=NAME enter a name
-u URL, --url=URL enter an url
martin at ubuntu:~ $ ./test.py --version
3.1415926
martin at ubuntu:~ $ ./test.py
usage: show OptionParser
test.py: error: specify both name and url
martin at ubuntu:~ $
More information about the Python-list
mailing list