Parse command line arguments into a dictionary. This does not support lists as values.
(
args: Iterable[str],
)
| 11 | |
| 12 | |
| 13 | def parse_args( |
| 14 | args: Iterable[str], |
| 15 | ) -> SerializedCLIArgs: |
| 16 | """ |
| 17 | Parse command line arguments into a dictionary. |
| 18 | |
| 19 | This does not support lists as values. |
| 20 | """ |
| 21 | args_dict: SerializedCLIArgs = {} |
| 22 | |
| 23 | # Combine any arguments that are split by spaces |
| 24 | new_args: list[str] = [] |
| 25 | for arg in args: |
| 26 | if arg.startswith(("-", "--")): |
| 27 | new_args.append(arg) |
| 28 | elif new_args: |
| 29 | new_args[-1] += f" {arg}" |
| 30 | |
| 31 | for arg in new_args: |
| 32 | if arg.startswith(("-", "--")): |
| 33 | # Strip leading dashes |
| 34 | arg = arg.lstrip("-") |
| 35 | key: str |
| 36 | value: Any |
| 37 | |
| 38 | if "=" in arg: |
| 39 | key, value = arg.split("=", 1) |
| 40 | elif " " in arg: |
| 41 | key, value = arg.split(" ", 1) |
| 42 | key = key.strip() |
| 43 | value = value.strip() |
| 44 | else: |
| 45 | key = arg |
| 46 | value = "" |
| 47 | |
| 48 | # Try numeric conversion |
| 49 | try: |
| 50 | value = int(value) |
| 51 | except ValueError: |
| 52 | try: |
| 53 | value = float(value) |
| 54 | except ValueError: |
| 55 | pass |
| 56 | |
| 57 | # Try boolean conversion |
| 58 | if value == "True" or value == "true": |
| 59 | value = True |
| 60 | elif value == "false" or value == "False": |
| 61 | value = False |
| 62 | |
| 63 | # Create a list for duplicate arguments |
| 64 | if key in args_dict: |
| 65 | current = args_dict[key] |
| 66 | if isinstance(current, list): |
| 67 | current.append(value) |
| 68 | else: |
| 69 | args_dict[key] = [current, value] |
| 70 | else: |
searching dependent graphs…