You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python argparse可选参数配置咨询:实现多组合命令行用法

Using argparse to Support Flexible File/Function/Mode Command-Line Usage

Absolutely, argparse is more than capable of handling your desired command-line patterns! Let's walk through exactly how to set this up, with code examples and straightforward explanations.

Core Approach

The key to making this work is structuring the arguments to match your requirements:

  • --file is required (since all three usage patterns depend on it)
  • --function and --mode are both optional with no mutual exclusivity — they can be used alone or together
  • We’ll set a default value for --mode so it falls back to your desired default when not specified

Complete Code Example

import argparse

def main():
    # Initialize the argument parser with a clear description
    parser = argparse.ArgumentParser(description="Process files with optional function targeting and mode selection.")
    
    # Required file parameter — users must provide this every time
    parser.add_argument('--file', required=True, help='Path to the file you want to process')
    
    # Optional function parameter — only provided if targeting a specific function
    parser.add_argument('--function', help='Name of the function to apply processing to (omit to process the whole file)')
    
    # Optional mode parameter with a default value
    # Replace 'default_mode' with your actual default mode name
    parser.add_argument('--mode', default='default_mode', help='Processing mode to use (default: default_mode)')
    
    # Parse the incoming command-line arguments
    args = parser.parse_args()
    
    # Handle the three scenarios in your business logic
    if args.function is not None:
        # Scenario 1 or 2: Targeting a specific function
        active_mode = args.mode  # Uses default if user didn't specify
        print(f"Applying mode '{active_mode}' to function '{args.function}' in file '{args.file}'")
        # Replace this print with your actual function-processing code
    else:
        # Scenario 3: Processing the entire file
        print(f"Applying mode '{args.mode}' to entire file '{args.file}'")
        # Replace this print with your actual file-processing code

if __name__ == "__main__":
    main()

Testing the Three Usage Patterns

Let’s verify each of your desired commands works as expected:

  1. Full command with all parameters:

    prog --file my_script.py --function calculate_total --mode verbose
    

    Output:

    Applying mode 'verbose' to function 'calculate_total' in file 'my_script.py'
    
  2. File + Function (uses default mode):

    prog --file my_script.py --function calculate_total
    

    Output:

    Applying mode 'default_mode' to function 'calculate_total' in file 'my_script.py'
    
  3. File + Mode (applies to whole file):

    prog --file my_script.py --mode fast_process
    

    Output:

    Applying mode 'fast_process' to entire file 'my_script.py'
    

Quick Notes

  • If you ever need to enforce that at least one of --function or --mode is provided (your question doesn’t mention this, but it’s a common edge case), you can add custom validation after parsing the arguments.
  • The help strings are fully customizable — update them to match your program’s actual functionality for clarity.
  • The print statements in the logic block are just placeholders; swap them out with your actual processing code based on the arguments.

内容的提问来源于stack exchange,提问作者learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:21:21