-
Notifications
You must be signed in to change notification settings - Fork 0
/
argparse_actions.py
34 lines (30 loc) · 1.33 KB
/
argparse_actions.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
import argparse
import json
class Actions:
@staticmethod
def ReadFromFile():
"""Generates an argparse.Action that loads configuration arguments
from a file
Returns: argparse.Action
"""
# define class
class ReadFromFileAction(argparse.Action):
"""Opens the file in the value of the argument, reads the
'command' field and loads all the key/value pairs to the namespace
"""
def __init__(self, option_strings, dest, nargs=None, **kwargs):
if nargs is not None:
raise ValueError("nargs not allowed")
super(ReadFromFileAction, self).__init__(option_strings, dest,
**kwargs)
def __call__(self, parser, namespace, values, option_string=None):
with open(values, 'r') as f:
config = json.load(f)
for key, value in config['configuration'].items():
if key is self.dest: continue
setattr(namespace, key, value)
setattr(namespace, "resume_training", True)
print('%r %r %r' % (namespace, values, option_string))
setattr(namespace, self.dest, values)
# return class
return ReadFromFileAction