Most pythonic way of accepting arguments using optparse

﹥>﹥吖頭↗ 提交于 2019-12-03 16:33:44

argparse is still an option, it's just not built into 2.6. You can still install it like any 3rd party package (for example, using easy_install argparse).

An example of code for this would be:

import sys
import argparse

p = argparse.ArgumentParser(description="script.py")
p.add_argument("-s", dest="string")
p.add_argument("-f", dest="infile")

args = p.parse_args()

if args.infile == None and args.string == None:
    print "Must be given either a string or a file"
    sys.exit(1)
if args.infile != None and args.string != None:
    print "Must be given either a string or a file, not both"
    sys.exit(1)
if args.infile:
    # process the input file one string at a time
if args.string:
    # process the single string
Thomas Vander Stichele

See my answer here: What's the best way to grab/parse command line arguments passed to a Python script?

As a shortcut, here's some sample code:

import optparse

parser = optparse.OptionParser()

parser.add_option('-q', '--query',
    action="store", dest="query",
    help="query string", default="spam")

options, args = parser.parse_args()

print 'Query string:', options.query
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!