-
Notifications
You must be signed in to change notification settings - Fork 1
/
blargs.py
1565 lines (1114 loc) · 41.9 KB
/
blargs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
blargs command line parser
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Easy argument parsing with powerful dependency support.
:copyright: (c) 2012 by Karl Gyllstrom
:license: BSD (see LICENSE.txt)
'''
from __future__ import print_function
import os
import operator
from functools import partial, wraps
from itertools import starmap, permutations
import sys
if sys.version_info[0] == 3:
iterkeys = lambda x: x.keys()
iteritems = lambda x: iter(x.items())
isstring = lambda x: isinstance(x, str)
from urllib.parse import urlparse
xrange = range
import configparser as cpars
else:
iterkeys = lambda x: x.iterkeys()
iteritems = lambda x: x.iteritems()
isstring = lambda x: isinstance(x, basestring)
from urlparse import urlparse
import ConfigParser as cpars
class Multidict(object):
def __init__(self, dictionary=None):
self._values = {}
if dictionary is not None:
# XXX should we make sure dictionary conforms to our schema?
self._values.update(dictionary)
def __delitem__(self, key):
return self._values.__delitem__(key)
def __contains__(self, key):
return self._values.__contains__(key)
def copy(self):
return Multidict(self._values.copy())
def get(self, key):
return self._values.get(key)
def __str__(self):
return self._values.__str__()
def overwrite(self, key, value):
self._values[key] = value
def __setitem__(self, key, value):
if key in self._values:
v = self._values[key]
if not isinstance(v, list):
v = [v]
value = v + [value]
self._values[key] = value
def __getitem__(self, key):
return self._values.__getitem__(key)
def __iter__(self):
return iteritems(self._values)
class _ConfigCaster(object):
def __init__(self, parent):
self._parent = parent
def __call__(self, filename):
cfp = cpars.ConfigParser()
cfp.readfp(open(filename))
for sec in cfp.sections():
for key, value in cfp.items(sec):
yield key, value
class _RangeCaster(object):
def __call__(self, value):
def raise_error():
raise FormatError(('%s is not range format: N:N+i, N-N+i, or N'
+ ' N+i') % value)
splitter = None
for char in (' :-'):
if char in value:
splitter = char
break
if splitter:
toks = value.split(splitter)
else:
toks = [value]
if not (1 <= len(toks) <= 3):
raise_error()
try:
return xrange(*[int(y) for y in toks])
except ValueError:
raise_error()
class _DirectoryOpenerCaster(object):
def __init__(self, create):
self._create = create
def __call__(self, name):
if not os.path.exists(name):
if self._create:
os.makedirs(name)
return name
raise IOError('%s does not exist' % name)
if not os.path.isdir(name):
raise IOError('%s is not directory' % name)
return name
class _FileOpenerCaster(object):
def __init__(self, mode=None, buffering=None):
self._kw = {}
if mode is not None:
self._kw['mode'] = mode
if buffering is not None:
self._kw['buffering'] = buffering
def __call__(self, *args):
return open(*args, **self._kw)
# ---------- decorators ---------- #
def _names_to_options(f):
@wraps(f)
def inner(*args, **kwargs):
new_args = []
for arg in args[1:]:
if isstring(arg):
arg = args[0]._options[arg]
new_args.append(arg)
return f(*[args[0]] + new_args, **kwargs)
return inner
def _options_to_names(f):
''' Convert any :class:`Option`s to names. '''
@wraps(f)
def inner(*args, **kwargs):
new_args = []
for arg in args[1:]:
if isinstance(arg, Option) and not isinstance(arg, Group):
arg = arg.argname
new_args.append(arg)
return f(*[args[0]] + new_args, **kwargs)
return inner
def _verify_args_exist(f):
@wraps(f)
def inner(*args, **kwargs):
def raise_error(name):
raise ValueError('%s not known' % name)
self = args[0]
for arg in args[1:]:
if isstring(arg) and arg not in self._readers:
raise_error(arg)
return f(*args, **kwargs)
return inner
def _localize_all(f):
@wraps(f)
def inner(*args, **kwargs):
args = list(args)
self = args[0]
new_args = []
for arg in args[1:]:
if isstring(arg):
arg = self._localize(arg)
new_args.append(arg)
args[1:] = new_args
return f(*args, **kwargs)
return inner
def localize(f):
@wraps(f)
def inner(*args, **kwargs):
args = list(args)
self = args[0]
# args[1:] = [self._localize(x) for x in args[1]]
args[1] = self._localize(args[1])
return f(*args, **kwargs)
return inner
# ---------- end decorators ---------- #
# ---------- exceptions ---------- #
class ArgumentError(ValueError):
''' Root class of all arguments that are thrown due to user input which
violates a rule set by the parser. In other words, errors of this type
should be caught and communicated to the user some how. The default
behavior is to signal the particular error and show the `usage`.'''
pass
class FormatError(ArgumentError):
''' Argument not formatted correctly. '''
pass
class ConditionError(ArgumentError):
''' Condition not met. '''
def __init__(self, argname, condition):
super(ConditionError, self).__init__()
self.argname = argname
self.condition = condition
def __str__(self):
return '%s required unless %s' % (self.argname, self.condition)
class MissingRequiredArgumentError(ArgumentError):
''' Required argument not specified. '''
def __init__(self, arg):
if isinstance(arg, Option):
arg = arg.argname
super(MissingRequiredArgumentError, self).__init__(
'No value passed for %s' % arg)
class ManyAllowedNoneSpecifiedArgumentError(ArgumentError):
''' An argument out of a list of required is missing.
e.g., one of -a and -b is required and neither is specified. '''
def __init__(self, allowed):
super(ManyAllowedNoneSpecifiedArgumentError, self).__init__(('[%s] not'
+ ' specified') % ', '.join(sorted(map(str, allowed))))
class UnspecifiedArgumentError(ArgumentError):
''' User supplies argument that isn't specified. '''
message = 'illegal option {0}'
def __init__(self, arg):
super(UnspecifiedArgumentError,
self).__init__(UnspecifiedArgumentError.message.format(arg))
class MultipleSpecifiedArgumentError(ArgumentError):
''' Multiple of the same argument specified. '''
pass
class DependencyError(ArgumentError):
''' User specified an argument that requires another, unspecified argument.
'''
def __init__(self, arg1, arg2):
super(DependencyError, self).__init__('%s requires %s' % (arg1, arg2))
class ConflictError(ArgumentError):
''' User specified an argument that conflicts another specified argument.
'''
def __init__(self, offender1, offender2):
super(ConflictError, self).__init__('%s conflicts with %s' %
(offender1, offender2))
class FailedConditionError(ArgumentError):
''' Condition failed. '''
pass
class MissingValueError(ArgumentError):
''' Argument flag specified without value. '''
pass
class InvalidEnumValueError(ArgumentError):
''' Enum value provided not allowed. '''
pass
# ---------- end exceptions ---------- #
class Condition(object):
def __init__(self):
self._other_conditions = []
self._and = True
self._neg = False
def _copy(self):
c = self.__new__(self.__class__)
c._other_conditions = self._other_conditions[:]
c._and = self._and
c._neg = self._neg
return c
def __neg__(self):
c = self._copy()
c._neg = True
return c
def _inner_satisfied(self, parsed):
raise NotImplementedError
def and_(self, condition):
if not self._and:
raise ValueError('and/or both specified')
c = self._copy()
c._other_conditions.append(condition)
return c
def or_(self, condition):
c = self._copy()
c._other_conditions.append(condition)
c._and = False
return c
def _is_satisfied(self, parsed):
def _inner():
for n in self._other_conditions:
if not n._is_satisfied(parsed):
if self._and:
return False
elif not self._and:
return True
return self._inner_satisfied(parsed)
result = _inner()
if self._neg:
result = not result
return result
class _CallableCondition(Condition):
def __init__(self, call, main, other):
super(_CallableCondition, self).__init__()
self._call = call
self._main = main
self._other = other
def _copy(self):
c = super(_CallableCondition, self)._copy()
c._call = self._call
c._main = self._main
c._other = self._other
return c
def _inner_satisfied(self, parsed):
operands = []
for item in (self._main, self._other):
if isinstance(item, Option):
v = parsed.get(item.argname)
if isinstance(v, list):
v = [vi.getvalue() for vi in v]
else:
v = [v.getvalue()]
else:
v = [item]
operands.append(v)
for x1 in operands[0]:
for x2 in operands[1]:
if not self._call(x1, x2):
return False
return True
def __repr__(self):
x = self._main.argname
names = {operator.le: '<=',
operator.lt: '<',
operator.gt: '>',
operator.ge: '>=',
operator.eq: '==',
operator.ne: '!='}
x += ' ' + names[self._call] + ' ' + str(self._other)
return x
class Option(Condition):
''' Do not construct directly, as it will not be tethered to a
:class:`Parser` object and so will not be handled in argument parsing. '''
def __init__(self, argname, parser):
super(Option, self).__init__()
self.argname = argname
self._parser = parser
self._conditions = []
self._allows_multiple = False
self._description = None
def _copy(self):
c = super(Option, self)._copy()
c.argname = self.argname
c._parser = self._parser
c._conditions = self._conditions
return c
def described_as(self, description):
'''
Add a description to this argument, to be displayed when users trigger the help message.
:param description: description of argument
'''
self._description = description
return self
def requires(self, *conditions):
'''
Specify other options/conditions which this argument requires.
:param conditions: required conditions
:type others: sequence of either :class:`Option` or :class:`Condition`
'''
[self._parser._set_requires(self.argname, x) for x in conditions]
return self
def conflicts(self, *conditions):
''' Specify other conditions which this argument conflicts with.
:param conditions: conflicting options/conditions
:type conditions: sequence of either :class:`Option` or
:class:`Condition`
'''
[self._parser._set_conflicts(self.argname, x) for x in conditions]
return self
def shorthand(self, alias):
'''
Set shorthand for this argument. Shorthand arguments are 1
character in length and are prefixed by a single '-'. For example:
::
parser.str('option').shorthand('o')
would cause '--option' and '-o' to be alias argument labels when
invoked on the command line.
:param alias: alias of argument
'''
self._parser._add_shorthand(self.argname, alias)
return self
def default(self, value):
''' Provide a default value for this argument. '''
self._parser._set_default(self.argname, value)
return self
def environment(self):
''' Pull argument value from OS environment if unspecified. The case of
the argument name, all lower, and all upper are all tried. For example,
if the argument name is `Port`, the following names will be used for
environment lookups: `Port`, `port`, `PORT`.
::
with Parser(locals()) as p:
p.int('port').environment()
Both command lines work:
::
python test.py --port 5000
export PORT=5000; python test.py
'''
default = os.environ.get(self.argname)
if default is None:
default = os.environ.get(self.argname.lower())
if default is None:
default = os.environ.get(self.argname.upper())
if default is not None:
# XXX not tested
return self.default(default)
return self
def cast(self, cast):
''' Provide a casting value for this argument. '''
self._parser._readers[self.argname] = Caster(
self._parser._readers[self.argname], cast)
return self
def required(self):
''' Indicate that this argument is required. '''
self._parser._set_required(self.argname)
return self
def if_(self, condition):
''' Argument is required if ``conditions``. '''
self._parser._set_required(self.argname, [-condition])
return self
def unless(self, condition):
''' Argument is required unless ``conditions``. '''
self._parser._set_required(self.argname, [condition])
return self
def unspecified_default(self):
''' Indicate that values passed without argument labels will be
attributed to this argument. '''
self._parser._set_unspecified_default(self.argname)
return self
def multiple(self):
''' Indicate that the argument can be specified multiple times. '''
self._allows_multiple = True
return self
# --- conditions
def _inner_satisfied(self, parsed):
v = parsed.get(self.argname)
if not isinstance(v, list):
v = [v]
return all(x.is_resolvable() for x in v)
def _make_condition(self, func, other):
return _CallableCondition(func, self, other)
def __le__(self, other):
return self._make_condition(operator.__le__, other)
def __lt__(self, other):
return self._make_condition(operator.__lt__, other)
def __gt__(self, other):
return self._make_condition(operator.__gt__, other)
def __ge__(self, other):
return self._make_condition(operator.__ge__, other)
def __eq__(self, other):
return self._make_condition(operator.__eq__, other)
def __ne__(self, other):
return self._make_condition(operator.__ne__, other)
def __hash__(self):
return hash(str(self.argname))
# -- private access methods
def _isrequired(self):
return self in self._parser._required
def _getconflicts(self):
return self._parser._conflicts.get(self, [])
def _getreqs(self):
return self._parser._requires.get(self, [])
def _alias(self):
return self._parser._source_to_alias.get(self.argname)
def __str__(self):
v = '%s%s' % (self._parser._double_prefix, self.argname)
alias = self._alias()
if alias:
v += '/%s%s' % (self._parser._single_prefix, alias)
return v
# ---------- Argument readers ---------- #
# Argument readers help parse the command line. The flow is as follows:
#
# 1) We create a reader for each argument based on the type specified by the
# programmer (e.g., a bool will get a _FlagArgumentReader
#
# 2) The reader is used when we hit the argument label
class _ArgumentReader(object):
class _UNSPECIFIED(object):
def __repr__(self):
return 'UNSPECIFIED'
UNSPECIFIED = _UNSPECIFIED()
def __init__(self, parent):
self.value = _ArgumentReader.UNSPECIFIED
self.parent = parent
self._default = _ArgumentReader.UNSPECIFIED
self._init()
def fresh_copy(self):
return self.__class__(self.parent)
def _init(self):
pass
def activate(self):
pass
def _set_default(self, default):
self._default = default
def consume_or_skip(self, arg):
raise NotImplementedError
def is_specified(self):
return self.value is not _ArgumentReader.UNSPECIFIED
def is_resolvable(self):
return (self.is_specified() or self._default is not
_ArgumentReader.UNSPECIFIED)
def default(self):
if self._default is not _ArgumentReader.UNSPECIFIED:
return self._default
return self.__class__.class_default()
@classmethod
def class_default(cls):
return _ArgumentReader.UNSPECIFIED
def _get(self):
raise NotImplementedError
def getvalue(self):
if self.is_specified():
return self._get()
return self.default()
class _MultiWordArgumentReader(_ArgumentReader):
def consume_or_skip(self, arg):
if self.parent._is_argument_label(arg):
return False
if not self.is_specified():
self.value = []
self.value.append(arg)
return True
def _get(self):
if not self.is_specified() or len(self.value) == 0:
# XXX
raise MissingValueError
return ' '.join(self.value)
class _FlagArgumentReader(_ArgumentReader):
def _init(self):
self.value = False
def activate(self):
self.value = True
def is_resolvable(self):
return self.value
def consume_or_skip(self, arg):
return False
def _get(self):
return self.value
@classmethod
def class_default(cls):
return False
class _SingleWordReader(_ArgumentReader):
def consume_or_skip(self, arg):
if self.is_specified():
return False
self.value = arg
return True
def _get(self):
if not self.is_specified():
raise MissingValueError
return self.value
class Caster(object):
def __init__(self, reader, cast):
self._reader = reader
self._cast = cast
def fresh_copy(self):
# XXX does _cast need to be copied too?
return self.__class__(self._reader.fresh_copy(), self._cast)
def activate(self):
self._reader.activate()
def getvalue(self):
try:
v = self._reader.getvalue()
if v is _ArgumentReader.UNSPECIFIED:
return None
return self._cast(v)
except ValueError:
raise FormatError
def is_resolvable(self):
return self._reader.is_resolvable()
def consume_or_skip(self, arg):
return self._reader.consume_or_skip(arg)
def is_specified(self):
return self._reader.is_specified()
def _set_default(self, default):
self._reader._set_default(default)
# ---------- Argument readers ---------- #
class Group(Option):
def __init__(self, parser, *names):
self._parser = parser
# super(Group, self).__init__('group', parser)
self._names = names
self.argname = self
def default(self, name):
if name not in self._names:
raise ValueError('%s not in group' % name)
self._default = name
return self
def _is_satisfied(self, parsed):
for item in self._names:
if item._is_satisfied(parsed):
return True
return False
def __str__(self):
return ', '.join([str(name) for name in self._names])
class Parser(object):
''' Command line parser. '''
def __init__(self, store=None):
self._options = {}
self._readers = {}
self._extras = []
self._unspecified_default = None
# dict of A (required) -> args that could replace A if A is not
# specified
self._required = {}
# dict of A -> args that A depends on
self._requires = {}
# dict of A -> args that A conflicts with
self._conflicts = {}
self._alias = {}
self._source_to_alias = {}
# convert arg labels to understore in value dict
self._to_underscore = False
# prefix to shorthand args
self._single_prefix = '-'
# prefix to fullname args
self._double_prefix = '--'
# help message
self._help_prefix = None
self._sys_exit_error = SystemExit
self.out = sys.stdout # XXX not documented
# set by user
self._init_user_set(store)
self.flag('help').shorthand('h').described_as('Print help message.')
def _init_user_set(self, store=None):
if store is None:
store = {}
self._store = store
self._namemaps = {}
self._rnamemaps = {}
def _argument_exists(self, name_or_alias):
return name_or_alias in self._readers or name_or_alias in self._alias
def set_help_prefix(self, message):
''' Indicate text to appear before argument list when the ``help``
function is triggered. '''
self._help_prefix = message
return self
def underscore(self):
''' Convert '-' to '_' in argument names. This is enabled if
``with_locals`` is used, as variable naming rules are applied. '''
self._to_underscore = True
return self
def set_single_prefix(self, flag):
''' Set the single flag prefix. This appears before short arguments
(e.g., -a). '''
if self._double_prefix in flag:
raise ValueError(
'single_prefix cannot be superset of double_prefix')
self._single_prefix = flag
return self
def set_double_prefix(self, flag):
''' Set the double flag prefix. This appears before long arguments
(e.g., --arg). '''
if flag in self._single_prefix:
raise ValueError('single_flag cannot be superset of double_flag')
self._double_prefix = flag
return self
def use_aliases(self):
raise NotImplementedError
@classmethod
def with_locals(cls):
''' Create :class:`Parser` using locals() dict. '''
import inspect
vals = inspect.currentframe().f_back.f_locals
return Parser(vals).underscore()
# --- types --- #
def config(self, name):
'''
Add configuration file, whose key/value pairs will provide/replace any
arguments created for this parser. Configuration format should be INI.
For example:
::
with Parser() as p:
p.int('a')
p.str('b')
p.config('conf')
Now, arg ``a`` can be specfied on the command line, or in the
configuration file passed to ``conf``. For example:
::
python test.py --a 3
python test.py --conf myconfig.cfg
Where myconfig.cfg:
::
[myconfigfile]
a = 5
b = 9
x = 'hello'
Note that any parameters in the config that aren't created as
arguments via this parser are ignored. In the example above, the
values of variables ``a`` and ``b`` would be assigned, while ``x``
would be ignored (as the developer did not create an ``x``
argument).
If an argument is specified both on the command line and within the
config file, it must be indicated as allowing multiple (via
:py:meth:`.multiple`).
'''
return self.str(name).cast(_ConfigCaster(self))
def enum(self, name, values):
arg = self.str(name)
cond = arg == values[0]
for v in values[1:]:
cond = cond.or_(arg == v)
return arg.requires(cond)
def int(self, name):
''' Add integer argument. '''
return self._add_option(name).cast(int)
def float(self, name):
''' Add float argument. '''
return self._add_option(name).cast(float)
# def enum(self, name, values):
# ''' Add enum type. '''
#
# def inner(value):
# if not value in values:
# raise InvalidEnumValueError()
# return value
#
# return self._add_option(name).cast(inner)
def str(self, name):
''' Add :py:class:`str` argument. '''
return self._add_option(name)
def range(self, name):
''' Range type. Accepts similar values to that of python's py:`range`
and py:`xrange`. Accepted delimiters are space, -, and :.
::
with Parser() as p:
p.range('values')
Now accepts: