Python命令行参数如何支持多参数组合输入?
I’ve tinkered with similar PAML workflow scripts before—having flexible model selection is a total lifesaver when you don’t want to rerun every single model just to test one or two. Let’s walk through a straightforward way to add this functionality using Python’s built-in argparse library, which keeps your command-line interface clean and easy to use.
Step 1: Define Your Supported Models
First, list out all the PAML models your script works with. Adjust this to match the models you actually use:
ALL_MODELS = ["M0", "M1a", "M2a", "M3", "M7", "M8"] # Customize to your model set
Step 2: Set Up Command-Line Arguments
We’ll use argparse to create three clear modes of operation:
- Default: Run all models
- Specify a single model to rerun
- Randomly pick two models to rerun
We’ll add a mutually exclusive group to prevent conflicting inputs (like trying to specify a model and request random two at the same time):
import argparse import random def parse_args(): parser = argparse.ArgumentParser(description="Update codeml.ctl and run PAML models with flexible selection") # Create a group where only one selection option can be used selection_group = parser.add_mutually_exclusive_group() # Option 1: Run a single specific model selection_group.add_argument( "-m", "--model", choices=ALL_MODELS, help="Run one specific model (e.g., -m M2a)" ) # Option 2: Randomly select two models selection_group.add_argument( "-r", "--random-two", action="store_true", help="Randomly pick and run two models from the full set" ) return parser.parse_args()
Step 3: Handle Model Selection Logic
Next, write a function to translate the user’s input into a list of models to run:
def get_selected_models(args): if args.model: # User wants a single model return [args.model] elif args.random_two: # Pick two unique random models (no duplicates) return random.sample(ALL_MODELS, 2) else: # Default: run all models return ALL_MODELS
Step 4: Integrate with Your Existing Script
Plug this into your existing code that updates codeml.ctl and executes PAML. Here’s how it might look:
def update_codeml_and_run(model): # Replace this with your existing logic: # 1. Update codeml.ctl with parameters for the target model # 2. Run PAML (e.g., using subprocess.run(["codeml"])) print(f"Processing model: {model}") if __name__ == "__main__": args = parse_args() selected_models = get_selected_models(args) for model in selected_models: update_codeml_and_run(model)
How to Use the Script
- Run all models (default behavior):
python your_script.py - Rerun a single model:
python your_script.py -m M0 - Run two random models:
python your_script.py -r
Bonus: Extra Validation
If you want to add safeguards (like ensuring the random selection never picks the same model twice, though random.sample already handles this) or custom error messages, you can extend the logic—but this base setup covers most common use cases.
内容的提问来源于stack exchange,提问作者CuriousDude

