selfboot / AnnotatedShadowSocks

Annotated shadowsocks(python version)
Other
3 stars 1 forks source link

Command line option parsing #2

Open selfboot opened 7 years ago

selfboot commented 7 years ago

The getopt module is the old-school command line option parser that supports the conventions established by the Unix function getopt(). It parses an argument sequence, such as sys.argv and returns a sequence of (option, argument) pairs and a sequence of non-option arguments.

Supported option syntax includes:

-a
-bval
-b val
--noarg
--witharg=val
--witharg val

The getopt function takes three arguments:

Ref:
getopt – Command line option parsing
C-style parser for command line options

selfboot commented 7 years ago

For demo.py:

import getopt
import sys

version = '1.0'
verbose = False
output_filename = 'default.out'

print 'ARGV      :', sys.argv[1:]

options, remainder = getopt.getopt(sys.argv[1:], 'o:v', ['output=', 
                                                         'verbose',
                                                         'version=',
                                                         ])
print 'OPTIONS   :', options

for opt, arg in options:
    if opt in ('-o', '--output'):
        output_filename = arg
    elif opt in ('-v', '--verbose'):
        verbose = True
    elif opt == '--version':
        version = arg

print 'VERSION   :', version
print 'VERBOSE   :', verbose
print 'OUTPUT    :', output_filename
print 'REMAINING :', remainder

$ python demo.py --output=foo ARGV : ['--output=foo'] OPTIONS : [('--output', 'foo')] VERSION : 1.0 VERBOSE : False OUTPUT : foo REMAINING : [] $ python demo.py --output ARGV : ['--output'] Traceback (most recent call last): File "demo.py", line 15, in 'version=', File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/getopt.py", line 88, in getopt opts, args = do_longs(opts, args[0][2:], longopts, args[1:]) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/getopt.py", line 156, in do_longs raise GetoptError('option --%s requires argument' % opt, opt) getopt.GetoptError: option --output requires argument

selfboot commented 7 years ago

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.