1# Copyright 2018 The Abseil Authors. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""Test helper for argparse_flags_test.""" 16 17import os 18import random 19 20from absl import app 21from absl import flags 22from absl.flags import argparse_flags 23 24FLAGS = flags.FLAGS 25 26flags.DEFINE_string('absl_echo', None, 'The echo message from absl.flags.') 27 28 29def parse_flags_simple(argv): 30 """Simple example for absl.flags + argparse.""" 31 parser = argparse_flags.ArgumentParser( 32 description='A simple example of argparse_flags.') 33 parser.add_argument( 34 '--argparse_echo', help='The echo message from argparse_flags') 35 return parser.parse_args(argv[1:]) 36 37 38def main_simple(args): 39 print('--absl_echo is', FLAGS.absl_echo) 40 print('--argparse_echo is', args.argparse_echo) 41 42 43def roll_dice(args): 44 print('Rolled a dice:', random.randint(1, args.num_faces)) 45 46 47def shuffle(args): 48 inputs = list(args.inputs) 49 random.shuffle(inputs) 50 print('Shuffled:', ' '.join(inputs)) 51 52 53def parse_flags_subcommands(argv): 54 """Subcommands example for absl.flags + argparse.""" 55 parser = argparse_flags.ArgumentParser( 56 description='A subcommands example of argparse_flags.') 57 parser.add_argument('--argparse_echo', 58 help='The echo message from argparse_flags') 59 60 subparsers = parser.add_subparsers(help='The command to execute.') 61 62 roll_dice_parser = subparsers.add_parser( 63 'roll_dice', help='Roll a dice.') 64 roll_dice_parser.add_argument('--num_faces', type=int, default=6) 65 roll_dice_parser.set_defaults(command=roll_dice) 66 67 shuffle_parser = subparsers.add_parser( 68 'shuffle', help='Shuffle inputs.') 69 shuffle_parser.add_argument( 70 'inputs', metavar='I', nargs='+', help='Inputs to shuffle.') 71 shuffle_parser.set_defaults(command=shuffle) 72 73 return parser.parse_args(argv[1:]) 74 75 76def main_subcommands(args): 77 main_simple(args) 78 args.command(args) 79 80 81if __name__ == '__main__': 82 main_func_name = os.environ['MAIN_FUNC'] 83 flags_parser_func_name = os.environ['FLAGS_PARSER_FUNC'] 84 app.run(main=globals()[main_func_name], 85 flags_parser=globals()[flags_parser_func_name]) 86