@@ -996,5 +996,75 @@ def _test(N=10_000):
996996 _os .register_at_fork (after_in_child = _inst .seed )
997997
998998
999+ # ------------------------------------------------------
1000+ # -------------- command-line interface ----------------
1001+
1002+
1003+ def _parse_args (arg_list : list [str ] | None ):
1004+ import argparse
1005+ parser = argparse .ArgumentParser (
1006+ formatter_class = argparse .RawTextHelpFormatter )
1007+ group = parser .add_mutually_exclusive_group ()
1008+ group .add_argument (
1009+ "-c" , "--choice" , nargs = "+" ,
1010+ help = "print a random choice" )
1011+ group .add_argument (
1012+ "-i" , "--integer" , type = int , metavar = "N" ,
1013+ help = "print a random integer between 1 and N inclusive" )
1014+ group .add_argument (
1015+ "-f" , "--float" , type = float , metavar = "N" ,
1016+ help = "print a random floating point number between 1 and N inclusive" )
1017+ group .add_argument (
1018+ "--test" , type = int , const = 10_000 , nargs = "?" ,
1019+ help = argparse .SUPPRESS )
1020+ parser .add_argument ("input" , nargs = "*" ,
1021+ help = """\
1022+ if no options given, output depends on the input
1023+ string or multiple: same as --choice
1024+ integer: same as --integer
1025+ float: same as --float""" )
1026+ args = parser .parse_args (arg_list )
1027+ return args , parser .format_help ()
1028+
1029+
1030+ def main (arg_list : list [str ] | None = None ) -> int | str :
1031+ args , help_text = _parse_args (arg_list )
1032+
1033+ # Explicit arguments
1034+ if args .choice :
1035+ return choice (args .choice )
1036+
1037+ if args .integer is not None :
1038+ return randint (1 , args .integer )
1039+
1040+ if args .float is not None :
1041+ return uniform (1 , args .float )
1042+
1043+ if args .test :
1044+ _test (args .test )
1045+ return ""
1046+
1047+ # No explicit argument, select based on input
1048+ if len (args .input ) == 1 :
1049+ val = args .input [0 ]
1050+ try :
1051+ # Is it an integer?
1052+ val = int (val )
1053+ return randint (1 , val )
1054+ except ValueError :
1055+ try :
1056+ # Is it a float?
1057+ val = float (val )
1058+ return uniform (1 , val )
1059+ except ValueError :
1060+ # Split in case of space-separated string: "a b c"
1061+ return choice (val .split ())
1062+
1063+ if len (args .input ) >= 2 :
1064+ return choice (args .input )
1065+
1066+ return help_text
1067+
1068+
9991069if __name__ == '__main__' :
1000- _test ( )
1070+ print ( main () )
0 commit comments