### Complete CLI Application Example Source: https://context7.com/nodeca/argparse/llms.txt This example demonstrates a full-featured CLI tool with subcommands, global options, and specific command arguments. It requires the 'argparse' and 'fs' modules. The script parses arguments and then executes logic based on the parsed command. ```javascript #!/usr/bin/env node const { ArgumentParser, ArgumentDefaultsHelpFormatter, BooleanOptionalAction } = require('argparse') const fs = require('fs') // Create main parser const parser = new ArgumentParser({ prog: 'datacli', description: 'Data processing command-line tool', epilog: 'Examples:\n datacli process input.csv --format json\n datacli validate data.json --strict', formatter_class: ArgumentDefaultsHelpFormatter }) // Global options parser.add_argument('-V', '--version', { action: 'version', version: '%(prog)s 1.0.0' }) parser.add_argument('-v', '--verbose', { action: 'count', default: 0, help: 'Increase verbosity' }) parser.add_argument('--config', { help: 'Configuration file' }) // Subcommands const subparsers = parser.add_subparsers({ dest: 'command', required: true }) // Process command const processCmd = subparsers.add_parser('process', { help: 'Process data files' }) processCmd.add_argument('input', { help: 'Input file path' }) processCmd.add_argument('-o', '--output', { default: 'stdout', help: 'Output destination' }) processCmd.add_argument('-f', '--format', { choices: ['json', 'csv', 'xml'], default: 'json', help: 'Output format' }) processCmd.add_argument('--pretty', { action: BooleanOptionalAction, default: true }) processCmd.add_argument('--filter', { action: 'append', default: [], help: 'Filter expressions' }) // Validate command const validateCmd = subparsers.add_parser('validate', { help: 'Validate data files' }) validateCmd.add_argument('files', { nargs: '+', help: 'Files to validate' }) validateCmd.add_argument('--strict', { action: 'store_true', help: 'Strict validation' }) validateCmd.add_argument('--schema', { help: 'JSON schema file' }) // Parse and execute const args = parser.parse_args() if (args.verbose >= 2) { console.log('Debug: Full arguments:', args) } else if (args.verbose >= 1) { console.log('Verbose mode enabled') } switch (args.command) { case 'process': console.log(`Processing ${args.input} -> ${args.output} (${args.format})`) console.log(`Filters: ${args.filter.join(', ') || 'none'}`) console.log(`Pretty print: ${args.pretty}`) break case 'validate': console.log(`Validating: ${args.files.join(', ')}`) console.log(`Strict mode: ${args.strict}`) if (args.schema) console.log(`Using schema: ${args.schema}`) break } // Example runs: // node cli.js process data.csv -f json -o output.json --filter "status=active" // node cli.js validate file1.json file2.json --strict --schema schema.json // node cli.js -vv process input.txt ``` -------------------------------- ### Argparse Help Message Example Source: https://github.com/nodeca/argparse/blob/master/README.md Displays the help message generated by argparse for the integer processing script. Shows positional and optional arguments with their descriptions. ```bash $ node prog.js -h usage: prog.js [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator optional arguments: -h, --help show this help message and exit --sum sum the integers (default: find the max) ``` -------------------------------- ### Set and Get Default Argument Values Source: https://context7.com/nodeca/argparse/llms.txt Illustrates how to set and retrieve default values for arguments programmatically using `set_defaults` and `get_default`. Shows how these defaults are included in parsed arguments. ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser() parser.add_argument('--format', { default: 'text' }) parser.add_argument('--verbose', { action: 'store_true' }) // Set defaults after argument definition parser.set_defaults({ format: 'json', log_level: 'info', custom_value: 42 }) // Get default for an argument console.log(parser.get_default('format')) // 'json' console.log(parser.get_default('log_level')) // 'info' console.log(parser.get_default('verbose')) // false // Defaults are included in parsed args const args = parser.parse_args([]) console.log(args.format) // 'json' console.log(args.log_level) // 'info' console.log(args.custom_value) // 42 console.log(args.verbose) // false ``` -------------------------------- ### Argparse Summation Example Source: https://github.com/nodeca/argparse/blob/master/README.md Runs the integer processing script with the '--sum' flag to calculate the sum of the provided integers. ```bash $ node prog.js 1 2 3 4 --sum 10 ``` -------------------------------- ### Argparse Max Value Example Source: https://github.com/nodeca/argparse/blob/master/README.md Runs the integer processing script without the '--sum' flag, defaulting to finding the maximum value among the provided integers. ```bash $ node prog.js 1 2 3 4 4 ``` -------------------------------- ### Custom Type Validation with TypeError Source: https://github.com/nodeca/argparse/blob/master/doc/migrate_v1_to_v2.md Provides an example of a custom type function that throws a `TypeError` for invalid input. Only `TypeError` exceptions are intercepted and converted to user-friendly error messages; other `Error` types are not. ```javascript parser.add_argument('--digit', { type: function digit(v) { if (!/^\d$/.test(v)) throw TypeError('not a digit') return +v } }) ``` -------------------------------- ### Programmatic Help and Usage Generation Source: https://context7.com/nodeca/argparse/llms.txt Generate help text and usage strings using format_help() and format_usage(). These methods can also print to custom streams. ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser({ prog: 'myapp', description: 'Example application', epilog: 'Run with --help for more information' }) parser.add_argument('-v', '--verbose', { action: 'store_true', help: 'Verbose mode' }) parser.add_argument('-o', '--output', { default: 'out.txt', help: 'Output file' }) parser.add_argument('input', { help: 'Input file' }) // Get full help text const helpText = parser.format_help() console.log(helpText) /* usage: myapp [-h] [-v] [-o OUTPUT] input Example application positional arguments: input Input file optional arguments: -h, --help show this help message and exit -v, --verbose Verbose mode -o OUTPUT, --output OUTPUT Output file Run with --help for more information */ // Get just usage string const usageText = parser.format_usage() console.log(usageText) // usage: myapp [-h] [-v] [-o OUTPUT] input // Print help/usage to custom stream const { Writable } = require('stream') const output = [] const customStream = new Writable({ write(chunk, encoding, callback) { output.push(chunk.toString()) callback() } }) parser.print_help(customStream) console.log(output.join('')) ``` -------------------------------- ### ArgumentParser Constructor Source: https://context7.com/nodeca/argparse/llms.txt Demonstrates how to create a new ArgumentParser instance with different configuration options. ```APIDOC ## ArgumentParser Constructor Creates a new argument parser instance with configurable options for program name, description, help formatting, and parsing behavior. ### Request Example ```javascript const { ArgumentParser } = require('argparse') // Basic parser with description const parser = new ArgumentParser({ prog: 'myprogram', description: 'A sample program that demonstrates argparse', epilog: 'For more information, visit our documentation' }) // Parser with custom formatting and prefix characters const customParser = new ArgumentParser({ prog: 'custom-cli', usage: '%(prog)s [options] ', description: 'Process input files with custom options', formatter_class: ArgumentParser.RawDescriptionHelpFormatter, prefix_chars: '-+', add_help: true, allow_abbrev: true, exit_on_error: true }) // Parser inheriting from parent parsers const parentParser = new ArgumentParser({ add_help: false }) parentParser.add_argument('--verbose', { action: 'store_true' }) const childParser = new ArgumentParser({ parents: [parentParser], description: 'Child parser inherits --verbose from parent' }) ``` ``` -------------------------------- ### Initialize ArgumentParser Source: https://context7.com/nodeca/argparse/llms.txt Creates a new argument parser instance with configurable options for program name, description, help formatting, and parsing behavior. Supports custom formatting and inheritance from parent parsers. ```javascript const { ArgumentParser } = require('argparse') // Basic parser with description const parser = new ArgumentParser({ prog: 'myprogram', description: 'A sample program that demonstrates argparse', epilog: 'For more information, visit our documentation' }) ``` ```javascript const customParser = new ArgumentParser({ prog: 'custom-cli', usage: '%(prog)s [options] ', description: 'Process input files with custom options', formatter_class: ArgumentParser.RawDescriptionHelpFormatter, prefix_chars: '-+', add_help: true, allow_abbrev: true, exit_on_error: true }) ``` ```javascript const parentParser = new ArgumentParser({ add_help: false }) parentParser.add_argument('--verbose', { action: 'store_true' }) const childParser = new ArgumentParser({ parents: [parentParser], description: 'Child parser inherits --verbose from parent' }) ``` -------------------------------- ### Customize Help Output with Formatters Source: https://context7.com/nodeca/argparse/llms.txt Demonstrates different formatter classes for customizing help output appearance. Each formatter class affects how descriptions and argument help text are displayed. ```javascript const { ArgumentParser, HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, ArgumentDefaultsHelpFormatter, MetavarTypeHelpFormatter } = require('argparse') // Default formatter - wraps text automatically const parser1 = new ArgumentParser({ formatter_class: HelpFormatter, description: 'This is a long description that will be\nwrapped automatically by the default formatter.' }) // RawDescriptionHelpFormatter - preserves description formatting const parser2 = new ArgumentParser({ formatter_class: RawDescriptionHelpFormatter, description: ` This description preserves formatting: - Line 1 - Line 2 Whitespace and newlines are kept intact. ` }) // RawTextHelpFormatter - preserves all help text formatting const parser3 = new ArgumentParser({ formatter_class: RawTextHelpFormatter, description: 'Preserves formatting in all help text' }) parser3.add_argument('--option', { help: `Multi-line help: - Preserves indentation - Keeps line breaks` }) // ArgumentDefaultsHelpFormatter - shows default values const parser4 = new ArgumentParser({ formatter_class: ArgumentDefaultsHelpFormatter, description: 'Shows default values in help' }) parser4.add_argument('--timeout', { type: 'int', default: 30, help: 'Request timeout' }) // Help shows: --timeout TIMEOUT Request timeout (default: 30) // MetavarTypeHelpFormatter - uses type name as metavar const parser5 = new ArgumentParser({ formatter_class: MetavarTypeHelpFormatter }) parser5.add_argument('--count', { type: 'int', help: 'Number of items' }) // Help shows: --count int Number of items ``` -------------------------------- ### Version Action for Version Information Source: https://context7.com/nodeca/argparse/llms.txt Add a version argument using the 'version' action to display program version information. The version string can include placeholders like %(prog)s. ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser({ prog: 'myapp', description: 'My Application' }) // Add version argument parser.add_argument('-V', '--version', { action: 'version', version: '%(prog)s 2.1.0' }) // With more detailed version info const parser2 = new ArgumentParser({ prog: 'cli-tool' }) parser2.add_argument('--version', { action: 'version', version: `%(prog)s version 1.0.0 Node.js ${process.version} Copyright (c) 2024 Example Inc.` }) // Running with --version prints version and exits // parser.parse_args(['--version']) // Output: myapp 2.1.0 ``` -------------------------------- ### Read Arguments from Files with Prefix Source: https://context7.com/nodeca/argparse/llms.txt Shows how to configure argparse to read arguments from files by specifying a prefix character. Demonstrates creating an arguments file, parsing arguments from it, and mixing file arguments with command-line arguments. ```javascript const { ArgumentParser } = require('argparse') const fs = require('fs') // Create args file fs.writeFileSync('args.txt', '--verbose\n--output\nresult.txt\ninput.txt') const parser = new ArgumentParser({ fromfile_prefix_chars: '@' // @ prefix reads from file }) parser.add_argument('--verbose', { action: 'store_true' }) parser.add_argument('--output') parser.add_argument('input') // Read arguments from file using @ prefix const args = parser.parse_args(['@args.txt']) // Equivalent to: parse_args(['--verbose', '--output', 'result.txt', 'input.txt']) // args.verbose = true // args.output = 'result.txt' // args.input = 'input.txt' // Mix file args with command line args const args2 = parser.parse_args(['@args.txt', '--output', 'override.txt']) // args2.output = 'override.txt' (command line overrides file) // Clean up fs.unlinkSync('args.txt') ``` -------------------------------- ### Create Sub-parsers for Subcommands Source: https://context7.com/nodeca/argparse/llms.txt Use `add_subparsers()` to create a CLI with multiple sub-commands. Each sub-parser can define its own set of arguments. Aliases can be provided for subcommands. ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser({ description: 'Git-like CLI example' }) // Global arguments parser.add_argument('--version', { action: 'version', version: '1.0.0' }) // Create subparsers const subparsers = parser.add_subparsers({ title: 'Commands', dest: 'command', help: 'Available commands' }) // 'clone' subcommand const cloneParser = subparsers.add_parser('clone', { help: 'Clone a repository', aliases: ['cl'] }) cloneParser.add_argument('url', { help: 'Repository URL' }) cloneParser.add_argument('--depth', { type: 'int', help: 'Clone depth' }) cloneParser.add_argument('--branch', '-b', { default: 'main', help: 'Branch to clone' }) // 'commit' subcommand const commitParser = subparsers.add_parser('commit', { help: 'Commit changes', aliases: ['ci'] }) commitParser.add_argument('-m', '--message', { required: true, help: 'Commit message' }) commitParser.add_argument('-a', '--all', { action: 'store_true', help: 'Stage all changes' }) commitParser.add_argument('--amend', { action: 'store_true', help: 'Amend previous commit' }) // 'push' subcommand const pushParser = subparsers.add_parser('push', { help: 'Push commits' }) pushParser.add_argument('remote', { nargs: '?', default: 'origin', help: 'Remote name' }) pushParser.add_argument('branch', { nargs: '?', help: 'Branch name' }) pushParser.add_argument('-f', '--force', { action: 'store_true', help: 'Force push' }) // Parse and handle commands const args = parser.parse_args(['commit', '-m', 'Initial commit', '-a']) // args.command = 'commit' // args.message = 'Initial commit' // args.all = true // Example with clone using alias const args2 = parser.parse_args(['cl', 'https://github.com/user/repo.git', '--depth', '1']) // args2.command = 'clone' // args2.url = 'https://github.com/user/repo.git' // args2.depth = 1 ``` -------------------------------- ### Parse Arguments into Namespace Objects Source: https://context7.com/nodeca/argparse/llms.txt Demonstrates how parsed arguments are returned as a Namespace object with attributes for each argument. Shows parsing into a default Namespace, an existing Namespace, and direct Namespace creation. ```javascript const { ArgumentParser, Namespace } = require('argparse') const parser = new ArgumentParser() parser.add_argument('--name') parser.add_argument('--count', { type: 'int' }) // Parse into default Namespace const args = parser.parse_args(['--name', 'test', '--count', '5']) console.log(args.name) // 'test' console.log(args.count) // 5 // Parse into existing Namespace with preset values const existingNs = new Namespace({ preset: 'value', count: 0 }) const args2 = parser.parse_args(['--name', 'override'], existingNs) console.log(args2.preset) // 'value' (preserved) console.log(args2.name) // 'override' console.log(args2.count) // 0 (preset value, not overridden) // Create Namespace directly const ns = new Namespace({ foo: 'bar', num: 42 }) console.log(ns.foo) // 'bar' console.log(ns.num) // 42 ``` -------------------------------- ### Add Version Argument Source: https://github.com/nodeca/argparse/blob/master/doc/migrate_v1_to_v2.md Shows the recommended way to handle version information using the `version` action in `add_argument`, replacing the deprecated `version` option. ```javascript parser.add_argument('-v', '--version', { action: 'version', version: '1.0.0' }) ``` -------------------------------- ### add_argument - Adding Optional Arguments Source: https://context7.com/nodeca/argparse/llms.txt Explains how to add optional arguments (flags) with short/long forms, various actions, and type/choice validations. ```APIDOC ## add_argument - Adding Optional Arguments Defines optional flags with short and long forms, supporting various actions like storing values, boolean flags, and counting occurrences. ### Parameters #### Query Parameters - **-v, --verbose** (boolean) - Optional - Enable verbose output - **-o, --output** (string) - Optional - Output file path (default: %(default)s) - **-c, --config** (string) - Required - Configuration file (required) - **-n, --num** (int) - Optional - Number of iterations - **-f, --format** (string) - Optional - Output format (choices: json, xml, csv, default: json) - **--range** (array) - Optional - Range of values (requires 2 integers) ### Request Example ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser() // Short and long options parser.add_argument('-v', '--verbose', { action: 'store_true', help: 'Enable verbose output' }) // Option with value parser.add_argument('-o', '--output', { dest: 'output_file', default: 'output.txt', help: 'Output file path (default: %(default)s)' }) // Required option parser.add_argument('-c', '--config', { required: true, help: 'Configuration file (required)' }) // Option with type conversion parser.add_argument('-n', '--num', { type: 'int', default: 10, help: 'Number of iterations' }) // Option with choices parser.add_argument('-f', '--format', { choices: ['json', 'xml', 'csv'], default: 'json', help: 'Output format' }) // Option with metavar for help display parser.add_argument('--range', { nargs: 2, type: 'int', metavar: ['START', 'END'], help: 'Range of values' }) const args = parser.parse_args(['-v', '-o', 'result.txt', '-c', 'app.conf', '-n', '20', '-f', 'csv']) // args.verbose = true // args.output_file = 'result.txt' // args.config = 'app.conf' // args.num = 20 // args.format = 'csv' ``` ``` -------------------------------- ### Add Argument with Help Message Source: https://github.com/nodeca/argparse/blob/master/doc/migrate_v1_to_v2.md Demonstrates the updated signature for `add_argument` where argument names are raw parameters, not an array. The old signature is supported but will show a deprecation message. ```javascript parser.add_argument('-h', '--help', { help: 'show this help message and exit' }) ``` -------------------------------- ### Use FileType for File Streams Source: https://context7.com/nodeca/argparse/llms.txt Employ the FileType factory to create arguments that automatically open files for reading or writing, returning streams. Use '-' to specify stdin/stdout. ```javascript const { ArgumentParser, FileType } = require('argparse') const parser = new ArgumentParser() // Read file (returns ReadStream) parser.add_argument('--input', { type: FileType('r'), help: 'Input file to read' }) // Write file (returns WriteStream) parser.add_argument('--output', { type: FileType('w'), help: 'Output file to write' }) // With encoding option parser.add_argument('--log', { type: FileType({ flags: 'a', encoding: 'utf8' }), help: 'Log file to append' }) // Using stdin/stdout with '-' parser.add_argument('infile', { nargs: '?', type: FileType('r'), default: process.stdin, help: 'Input file (default: stdin)' }) parser.add_argument('outfile', { nargs: '?', type: FileType('w'), default: process.stdout, help: 'Output file (default: stdout)' }) // Example: read from file, write to stdout const args = parser.parse_args(['--input', 'data.txt']) // args.input is a readable stream // Remember to close streams when done: // if (args.input.close) args.input.close() ``` -------------------------------- ### Boolean and Constant Actions Source: https://context7.com/nodeca/argparse/llms.txt Use 'store_true' and 'store_false' for boolean flags, and 'store_const' to store a fixed value. 'SUPPRESS' can hide arguments from help messages. ```javascript const { ArgumentParser, SUPPRESS } = require('argparse') const parser = new ArgumentParser() // Boolean true flag parser.add_argument('--debug', { action: 'store_true', help: 'Enable debug mode' }) // Boolean false flag (defaults to true) parser.add_argument('--no-cache', { action: 'store_false', dest: 'cache', help: 'Disable caching' }) // Store constant value parser.add_argument('--mode', { action: 'store_const', const: 'production', default: 'development', help: 'Set production mode' }) // Hidden argument (suppressed from help) parser.add_argument('--internal', { action: 'store_true', help: SUPPRESS }) const args = parser.parse_args(['--debug', '--no-cache', '--mode']) // args.debug = true // args.cache = false // args.mode = 'production' ``` -------------------------------- ### Option Object Initialization in Argparse Source: https://github.com/nodeca/argparse/blob/master/doc/port_difference.md When initializing ArgumentParser in Javascript, pass configuration options as a single object, unlike Python's direct keyword arguments. ```python # python allows keyword arguments parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]') ``` ```javascript // keyword arguments are passed as a single `options` object parser = argparse.ArgumentParser({ prog: 'PROG', usage: '%(prog)s [options]' }) ``` -------------------------------- ### Argparse Constants for Argument Behavior Source: https://context7.com/nodeca/argparse/llms.txt Illustrates how to use special constants (SUPPRESS, OPTIONAL, ZERO_OR_MORE, ONE_OR_MORE, REMAINDER) to configure argument parsing behavior, including hiding arguments, specifying the number of arguments, and capturing remaining arguments. ```javascript const { ArgumentParser, SUPPRESS, OPTIONAL, ZERO_OR_MORE, ONE_OR_MORE, REMAINDER } = require('argparse') const parser = new ArgumentParser() // SUPPRESS - hide argument from help and don't add to namespace parser.add_argument('--internal', { help: SUPPRESS, default: SUPPRESS }) // OPTIONAL (?) - zero or one argument parser.add_argument('--config', { nargs: OPTIONAL, // same as nargs: '?' const: 'default.conf', default: null, help: 'Config file (optional value)' }) // ZERO_OR_MORE (*) - zero or more arguments parser.add_argument('--include', { nargs: ZERO_OR_MORE, // same as nargs: '*' default: [], help: 'Include paths' }) // ONE_OR_MORE (+) - one or more arguments parser.add_argument('files', { nargs: ONE_OR_MORE, // same as nargs: '+' help: 'Files to process' }) // REMAINDER (...) - capture all remaining arguments parser.add_argument('command', { help: 'Command to run' }) parser.add_argument('args', { nargs: REMAINDER, // same as nargs: '...' help: 'Arguments for command' }) const args = parser.parse_args([ '--config', // uses const value since no arg given '--include', 'path1', 'path2', 'file1.txt', 'file2.txt', 'echo', 'hello', 'world', '--flag' // captured by REMAINDER ]) // args.config = 'default.conf' // args.include = ['path1', 'path2'] // args.files = ['file1.txt', 'file2.txt'] // args.command = 'echo' // args.args = ['hello', 'world', '--flag'] ``` -------------------------------- ### Append and Count Actions Source: https://context7.com/nodeca/argparse/llms.txt Use 'append' to collect multiple values into a list, 'append_const' to collect predefined constants, and 'count' to tally flag occurrences. ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser() // Append action - collect multiple values parser.add_argument('-i', '--include', { action: 'append', default: [], help: 'Include directory (can be specified multiple times)' }) // Append const - collect preset values parser.add_argument('--add-feature-a', { action: 'append_const', const: 'feature_a', dest: 'features', help: 'Enable feature A' }) parser.add_argument('--add-feature-b', { action: 'append_const', const: 'feature_b', dest: 'features', help: 'Enable feature B' }) // Count action - count occurrences parser.add_argument('-v', '--verbose', { action: 'count', default: 0, help: 'Increase verbosity (can be repeated: -v, -vv, -vvv)' }) const args = parser.parse_args([ '-i', '/usr/include', '-i', '/opt/include', '--add-feature-a', '--add-feature-b', '-vvv' ]) // args.include = ['/usr/include', '/opt/include'] // args.features = ['feature_a', 'feature_b'] // args.verbose = 3 ``` -------------------------------- ### add_argument - Adding Positional Arguments Source: https://context7.com/nodeca/argparse/llms.txt Details on how to define and add positional arguments to the parser, including handling multiple values and type conversions. ```APIDOC ## add_argument - Adding Positional Arguments Defines positional arguments that are required by position in the command line, with support for multiple values and type conversion. ### Parameters #### Path Parameters - **filename** (string) - Required - Input file to process - **count** (int) - Required - Number of items to process - **files** (array) - Required - One or more files to process - **output** (string) - Optional - Output destination (default: stdout) - **extras** (array) - Optional - Additional optional arguments ### Request Example ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser() // Single required positional argument parser.add_argument('filename', { help: 'Input file to process' }) // Positional with type conversion parser.add_argument('count', { type: 'int', help: 'Number of items to process' }) // Multiple positional arguments with nargs parser.add_argument('files', { nargs: '+', // One or more arguments help: 'One or more files to process' }) // Optional positional with default parser.add_argument('output', { nargs: '?', // Zero or one argument default: 'stdout', help: 'Output destination (default: stdout)' }) // Zero or more arguments parser.add_argument('extras', { nargs: '*', // Zero or more arguments default: [], help: 'Additional optional arguments' }) const args = parser.parse_args(['input.txt', '5', 'a.txt', 'b.txt', 'out.txt']) // args.filename = 'input.txt' // args.count = 5 // args.files = ['a.txt', 'b.txt'] // args.output = 'out.txt' ``` ``` -------------------------------- ### Custom ArgumentParser with Overridden exit() Source: https://github.com/nodeca/argparse/blob/master/doc/migrate_v1_to_v2.md Illustrates how to handle the deprecation of the `debug` option by overriding the `.exit()` method in a custom ArgumentParser class. ```javascript const argparse = require('argparse') class MyArgumentParser extends argparse.ArgumentParser { exit() { console.log('no exiting today') } } parser = new MyArgumentParser() ``` -------------------------------- ### Strict vs. Known Argument Parsing Source: https://context7.com/nodeca/argparse/llms.txt Use `parse_args` for strict parsing where unknown arguments cause an error. Use `parse_known_args` to return unknown arguments separately, useful for passing them to other processes. ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser() parser.add_argument('--verbose', { action: 'store_true' }) parser.add_argument('--output', { default: 'out.txt' }) parser.add_argument('input') // parse_args - strict parsing, errors on unknown arguments const args1 = parser.parse_args(['--verbose', 'input.txt']) // args1 = Namespace { verbose: true, output: 'out.txt', input: 'input.txt' } ``` ```javascript // parse_known_args - returns [namespace, remaining_args] // Useful for passing unknown args to another program const [args2, unknown] = parser.parse_known_args([ '--verbose', 'input.txt', '--unknown-flag', 'extra-value' ]) // args2 = Namespace { verbose: true, output: 'out.txt', input: 'input.txt' } // unknown = ['--unknown-flag', 'extra-value'] ``` -------------------------------- ### Specify Argument Type as String Source: https://github.com/nodeca/argparse/blob/master/doc/migrate_v1_to_v2.md Demonstrates the renaming of the `string` type to `str` for argument type specification. The old `string` type is supported but will show a deprecation message. ```javascript parser.add_argument('--foo', { type: 'str' }) ``` -------------------------------- ### Intermixed Argument Parsing Source: https://context7.com/nodeca/argparse/llms.txt Use `parse_intermixed_args` to allow positional and optional arguments to appear in any order in the command line. ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser() parser.add_argument('--verbose', { action: 'store_true' }) parser.add_argument('--output', { default: 'out.txt' }) parser.add_argument('input') // parse_intermixed_args - allows positionals and optionals to be intermixed const args3 = parser.parse_intermixed_args(['input.txt', '--verbose', '--output', 'result.txt']) // args3 = Namespace { verbose: true, output: 'result.txt', input: 'input.txt' } ``` -------------------------------- ### Extend Action for List Extension Source: https://context7.com/nodeca/argparse/llms.txt The 'extend' action allows an argument to add multiple items to a list. Use 'nargs' to specify how many values are expected. ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser() // Extend action - add multiple items to list parser.add_argument('--modules', { action: 'extend', nargs: '+', type: 'str', default: [], help: 'Modules to load' }) parser.add_argument('--plugins', { action: 'extend', nargs: '*', default: ['core'], help: 'Plugins to enable' }) const args = parser.parse_args([ '--modules', 'auth', 'logging', 'cache', '--plugins', 'metrics', 'tracing' ]) // args.modules = ['auth', 'logging', 'cache'] // args.plugins = ['core', 'metrics', 'tracing'] ``` -------------------------------- ### Organize Arguments with Groups Source: https://context7.com/nodeca/argparse/llms.txt Use ArgumentParser's add_argument_group method to logically group related arguments, improving the clarity and organization of help messages. ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser({ description: 'Database management tool' }) // Connection options group const connGroup = parser.add_argument_group({ title: 'Connection Options', description: 'Database connection settings' }) connGroup.add_argument('--host', { default: 'localhost', help: 'Database host' }) connGroup.add_argument('--port', { type: 'int', default: 5432, help: 'Database port' }) connGroup.add_argument('--user', { required: true, help: 'Database user' }) connGroup.add_argument('--password', { help: 'Database password' }) // Query options group const queryGroup = parser.add_argument_group({ title: 'Query Options', description: 'Options for query execution' }) queryGroup.add_argument('--timeout', { type: 'int', default: 30, help: 'Query timeout in seconds' }) queryGroup.add_argument('--limit', { type: 'int', help: 'Maximum rows to return' }) queryGroup.add_argument('--format', { choices: ['table', 'json', 'csv'], default: 'table' }) // Positional argument (not in a group) parser.add_argument('query', { help: 'SQL query to execute' }) const args = parser.parse_args([ '--host', 'db.example.com', '--user', 'admin', '--format', 'json', 'SELECT * FROM users' ]) ``` -------------------------------- ### Process Integers with Argparse Source: https://github.com/nodeca/argparse/blob/master/README.md Parses a list of integers and either sums them or finds the maximum. Use 'int' type for numeric arguments and 'nargs: '+' to accept multiple values. The 'accumulate' action stores a function, with 'default' providing a fallback. ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser({ description: 'Process some integers.' }) let sum = ints => ints.reduce((a, b) => a + b) let max = ints => ints.reduce((a, b) => a > b ? a : b) parser.add_argument('integers', { metavar: 'N', type: 'int', nargs: '+', help: 'an integer for the accumulator' }) parser.add_argument('--sum', { dest: 'accumulate', action: 'store_const', const: sum, default: max, help: 'sum the integers (default: find the max)' }); let args = parser.parse_args() console.log(args.accumulate(args.integers)) ``` -------------------------------- ### Error Handling with ArgumentParser Source: https://context7.com/nodeca/argparse/llms.txt Configure ArgumentParser to either exit on error or throw exceptions. Custom error handling can be implemented by overriding the exit and error methods. ```javascript const { ArgumentParser, ArgumentError, ArgumentTypeError } = require('argparse') // Default behavior: prints error and exits const parser1 = new ArgumentParser({ exit_on_error: true // default }) // Disable exit on error - throws ArgumentError instead const parser2 = new ArgumentParser({ exit_on_error: false }) parser2.add_argument('--count', { type: 'int', required: true }) try { parser2.parse_args(['--count', 'notanumber']) } catch (err) { if (err instanceof ArgumentError) { console.log('Argument error:', err.message) // "argument --count: invalid 'int' value: 'notanumber'" } } // Override exit method for custom handling class NoExitParser extends ArgumentParser { exit(status, message) { if (status !== 0) { throw new Error(message) } } error(message) { throw new Error(`Parse error: ${message}`) } } const parser3 = new NoExitParser() parser3.add_argument('--required', { required: true }) try { parser3.parse_args([]) } catch (err) { console.log('Custom error:', err.message) } ``` -------------------------------- ### Add Optional Arguments with Argparse Source: https://context7.com/nodeca/argparse/llms.txt Defines optional flags with short and long forms. Supports various actions like storing values, boolean flags, counting occurrences, type conversion, and choices. ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser() // Short and long options parser.add_argument('-v', '--verbose', { action: 'store_true', help: 'Enable verbose output' }) ``` ```javascript // Option with value parser.add_argument('-o', '--output', { dest: 'output_file', default: 'output.txt', help: 'Output file path (default: %(default)s)' }) ``` ```javascript // Required option parser.add_argument('-c', '--config', { required: true, help: 'Configuration file (required)' }) ``` ```javascript // Option with type conversion parser.add_argument('-n', '--num', { type: 'int', default: 10, help: 'Number of iterations' }) ``` ```javascript // Option with choices parser.add_argument('-f', '--format', { choices: ['json', 'xml', 'csv'], default: 'json', help: 'Output format' }) ``` ```javascript // Option with metavar for help display parser.add_argument('--range', { nargs: 2, type: 'int', metavar: ['START', 'END'], help: 'Range of values' }) ``` ```javascript const args = parser.parse_args(['-v', '-o', 'result.txt', '-c', 'app.conf', '-n', '20', '-f', 'csv']) // args.verbose = true // args.output_file = 'result.txt' // args.config = 'app.conf' // args.num = 20 // args.format = 'csv' ``` -------------------------------- ### Custom Argument Actions Source: https://context7.com/nodeca/argparse/llms.txt Define custom action classes to transform or validate argument values. Ensure the custom action class extends the base Action class and implements the call method. ```javascript const { ArgumentParser, Action } = require('argparse') // Custom action that validates and transforms value class UppercaseAction extends Action { call(parser, namespace, values, option_string) { // Transform value to uppercase and store namespace[this.dest] = values.toUpperCase() } } // Custom action that accumulates key=value pairs into object class KeyValueAction extends Action { call(parser, namespace, values, option_string) { if (!namespace[this.dest]) { namespace[this.dest] = {} } const [key, value] = values.split('=') namespace[this.dest][key] = value } } const parser = new ArgumentParser() parser.add_argument('--name', { action: UppercaseAction, help: 'Name (converted to uppercase)' }) parser.add_argument('-D', '--define', { action: KeyValueAction, dest: 'definitions', help: 'Define key=value pair' }) const args = parser.parse_args([ '--name', 'hello', '-D', 'foo=bar', '-D', 'debug=true' ]) // args.name = 'HELLO' // args.definitions = { foo: 'bar', debug: 'true' } ``` -------------------------------- ### Add Positional Arguments with Argparse Source: https://context7.com/nodeca/argparse/llms.txt Defines positional arguments that are required by position in the command line. Supports multiple values, type conversion, optional arguments with defaults, and zero or more arguments. ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser() // Single required positional argument parser.add_argument('filename', { help: 'Input file to process' }) ``` ```javascript // Positional with type conversion parser.add_argument('count', { type: 'int', help: 'Number of items to process' }) ``` ```javascript // Multiple positional arguments with nargs parser.add_argument('files', { nargs: '+', // One or more arguments help: 'One or more files to process' }) ``` ```javascript // Optional positional with default parser.add_argument('output', { nargs: '?', // Zero or one argument default: 'stdout', help: 'Output destination (default: stdout)' }) ``` ```javascript // Zero or more arguments parser.add_argument('extras', { nargs: '*', // Zero or more arguments default: [], help: 'Additional optional arguments' }) ``` ```javascript const args = parser.parse_args(['input.txt', '5', 'a.txt', 'b.txt', 'out.txt']) // args.filename = 'input.txt' // args.count = 5 // args.files = ['a.txt', 'b.txt'] // args.output = 'out.txt' ``` -------------------------------- ### Type Specification in Argparse Source: https://github.com/nodeca/argparse/blob/master/doc/port_difference.md Javascript uses string literals like 'int', 'float', or 'str' for type specification, whereas Python uses built-in types. ```python parser.add_argument('--foo', type=int) ``` ```javascript parser.add_argument('--foo', { type: 'int' }) ``` -------------------------------- ### BooleanOptionalAction for Flags Source: https://context7.com/nodeca/argparse/llms.txt BooleanOptionalAction automatically creates both a positive (--flag) and a negative (--no-flag) version for a boolean argument, simplifying boolean switch handling. ```javascript const { ArgumentParser, BooleanOptionalAction } = require('argparse') const parser = new ArgumentParser() // Automatically creates --feature and --no-feature parser.add_argument('--feature', { action: BooleanOptionalAction, default: true, help: 'Enable or disable feature' }) parser.add_argument('--logging', { action: BooleanOptionalAction, default: false, help: 'Enable or disable logging' }) // Usage: program --feature or program --no-feature const args1 = parser.parse_args(['--feature']) // args1.feature = true const args2 = parser.parse_args(['--no-feature']) // args2.feature = false const args3 = parser.parse_args(['--logging']) // args3.logging = true ``` -------------------------------- ### Define Custom Argument Types Source: https://context7.com/nodeca/argparse/llms.txt Use custom functions or ArgumentTypeError to parse argument values into specific types like positive integers, dates, or JSON objects. Ensure custom types throw errors for invalid input. ```javascript const { ArgumentParser, ArgumentTypeError } = require('argparse') const parser = new ArgumentParser() // Built-in types parser.add_argument('--count', { type: 'int', help: 'Integer value' }) parser.add_argument('--rate', { type: 'float', help: 'Float value' }) parser.add_argument('--name', { type: 'str', help: 'String value' }) // Custom type function function positiveInt(value) { const num = parseInt(value, 10) if (isNaN(num) || num <= 0) { throw new TypeError(`${value} is not a positive integer`) } return num } parser.add_argument('--port', { type: positiveInt, default: 8080, help: 'Port number (positive integer)' }) // Custom type with ArgumentTypeError for better messages function validDate(value) { const date = new Date(value) if (isNaN(date.getTime())) { throw new ArgumentTypeError(`Invalid date format: ${value}`) } return date } parser.add_argument('--since', { type: validDate, help: 'Start date (YYYY-MM-DD format)' }) // JSON type parser function jsonType(value) { try { return JSON.parse(value) } catch (e) { throw new TypeError(`Invalid JSON: ${value}`) } } parser.add_argument('--config', { type: jsonType, default: {}, help: 'JSON configuration object' }) const args = parser.parse_args([ '--count', '42', '--rate', '3.14', '--port', '3000', '--since', '2024-01-15', '--config', '{"debug":true}' ]) // args.count = 42 // args.rate = 3.14 // args.port = 3000 // args.since = Date object // args.config = { debug: true } ``` -------------------------------- ### Define Mutually Exclusive Argument Groups Source: https://context7.com/nodeca/argparse/llms.txt Use `add_mutually_exclusive_group()` to ensure that only one argument from a group can be provided. The group can be made required by setting `required: true`. ```javascript const { ArgumentParser } = require('argparse') const parser = new ArgumentParser() // Create mutually exclusive group const group = parser.add_mutually_exclusive_group() group.add_argument('--verbose', { action: 'store_true', help: 'Verbose output' }) group.add_argument('--quiet', { action: 'store_true', help: 'Quiet output' }) // Required mutually exclusive group const formatGroup = parser.add_mutually_exclusive_group({ required: true }) formatGroup.add_argument('--json', { action: 'store_true', help: 'Output as JSON' }) formatGroup.add_argument('--xml', { action: 'store_true', help: 'Output as XML' }) formatGroup.add_argument('--csv', { action: 'store_true', help: 'Output as CSV' }) // Can't use --verbose and --quiet together // Must use exactly one of --json, --xml, or --csv const args = parser.parse_args(['--verbose', '--json']) // args.verbose = true // args.quiet = false // args.json = true ``` -------------------------------- ### Argparse Invalid Argument Error Source: https://github.com/nodeca/argparse/blob/master/README.md Demonstrates the error message produced by argparse when non-integer values are provided for an argument expecting integers. ```bash $ node prog.js a b c usage: prog.js [-h] [--sum] N [N ...] prog.js: error: argument N: invalid 'int' value: 'a' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.