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

Python脚本支持ALL参数:如何遍历所有参数选项优化代码

Clean Solution for Handling ALL Parameter in Python Path Logic

Great question—duplicating code with if/else blocks gets messy fast, especially when you add new options later. Here's a DRY (Don't Repeat Yourself), scalable approach that uses iteration instead of repeated code:

Step-by-Step Implementation

1. Define Valid Types & Base Path

First, declare your allowed file types in a single, easy-to-update spot and set your parent folder:

import sys

# Centralize valid file types for simple maintenance
ALLOWED_TYPES = {'FOO', 'BAR', 'FOOBAR'}
parent_folder = 'C:/path/to/dir/'

2. Process Input Parameter

Normalize the input to handle case insensitivity, then determine which types to process:

# Clean and standardize the input argument
file_type_arg = sys.argv[1].strip().upper()

# Decide which types to process
if file_type_arg == 'ALL':
    types_to_process = ALLOWED_TYPES
elif file_type_arg in ALLOWED_TYPES:
    types_to_process = {file_type_arg}
else:
    # Raise a clear error for invalid inputs
    raise ValueError(
        f"Invalid type: '{file_type_arg}'. Allowed values: {', '.join(ALLOWED_TYPES)} or ALL"
    )

3. Iterate Over Types (No Code Duplication!)

Now loop through each type in your types_to_process collection—this works seamlessly for both single types and the ALL case:

for file_type in types_to_process:
    # Use f-strings for cleaner path concatenation (better than string addition)
    input_folder = f"{parent_folder}{file_type}_inventory"
    output_folder = f"{parent_folder}{file_type}_export"
    
    # Insert your existing processing logic here (the [...] from your original code)
    print(f"Processing {file_type}:")
    print(f"  Input Folder: {input_folder}")
    print(f"  Output Folder: {output_folder}")

Key Benefits

  • No code duplication: Your core processing logic lives in one place, even when handling multiple types via ALL
  • Easy to maintain: Add new file types by just updating the ALLOWED_TYPES set—no need to copy/paste code blocks
  • Robust input handling: Normalizes input and validates against allowed values, preventing unexpected errors
  • Readable: Uses f-strings for path building and clear variable names that make the code intent obvious

Bonus: Support Multiple Individual Types (Optional)

If you want to let users pass multiple types (e.g., FOO,BAR), you can extend the input handling with this quick addition:

# Handle comma-separated types (e.g., "FOO,BAR")
if ',' in file_type_arg:
    requested_types = {t.strip().upper() for t in file_type_arg.split(',')}
    invalid_types = requested_types - ALLOWED_TYPES
    if invalid_types:
        raise ValueError(f"Invalid types: {', '.join(invalid_types)}")
    types_to_process = requested_types

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:44:00