I eventually managed to do it by treating the FLAGS object as a dictionary, and then flattening the dictionary to a string of key=value.
Here is the code:
def build_string_from_dict(d, sep='__'):
fd = _flatten_dict(d)
return sep.join(['{}={}'.format(k, _value2str(fd[k])) for k in sorted(fd.keys())])
def _flatten_dict(d, parent_key='', sep='_'):
# from http://stackoverflow.com/a/6027615/2476373
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(_flatten_dict(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
flags_dict = vars(FLAGS)['__flags']
print build_string_from_dict(flags_dict)