Python模板模块开发需求:实现命令行与导入式双模式统一行为
Python Template Module: Dual Mode (CLI + Importable)
Got it, let's build this flexible Python template module step by step. This implementation covers all your requirements—working seamlessly as a standalone CLI script and as an importable module with reusable components.
Core Module Implementation (template.py)
import argparse import json import sys from typing import Any, Optional, Dict class JSONProcessor: """Core class to handle JSON processing logic.""" def process(self, input_data: Dict[str, Any]) -> Dict[str, Any]: """ Override this method with your actual processing logic. Example: Adds a "processed" flag to the input JSON. """ input_data["processed"] = True return input_data def load_input(source: Optional[str], input_str: Optional[str]) -> Dict[str, Any]: """Load JSON input from stdin, file, or string.""" if input_str: return json.loads(input_str) elif source: with open(source, 'r') as f: return json.load(f) else: # Read from stdin return json.load(sys.stdin) def write_output(data: Dict[str, Any], destination: Optional[str]) -> None: """Write JSON output to stdout or file.""" json_data = json.dumps(data, indent=2) if destination: with open(destination, 'w') as f: f.write(json_data) else: print(json_data) def main(): """CLI entry point.""" parser = argparse.ArgumentParser(description="Process JSON input with unified behavior.") # Input options (mutually exclusive) input_group = parser.add_mutually_exclusive_group() input_group.add_argument('-f', '--file', help="Path to input JSON file") input_group.add_argument('-s', '--string', help="Raw JSON string as input") # Output option parser.add_argument('-o', '--output', help="Path to save output JSON (defaults to stdout)") args = parser.parse_args() # Load input with error handling try: input_data = load_input(args.file, args.string) except json.JSONDecodeError as e: print(f"Invalid JSON input: {str(e)}", file=sys.stderr) sys.exit(1) except FileNotFoundError: print(f"Input file '{args.file}' does not exist.", file=sys.stderr) sys.exit(1) # Process data processor = JSONProcessor() output_data = processor.process(input_data) # Write output write_output(output_data, args.output) if __name__ == "__main__": main()
Key Features & Usage
1. Importable Mode (For Other Modules)
When imported, you can use the JSONProcessor class directly or extend it for custom logic:
from template import JSONProcessor # Use the base processor processor = JSONProcessor() input_obj = {"user": "john_doe", "action": "login"} processed_obj = processor.process(input_obj) print(processed_obj) # Output: {"user": "john_doe", "action": "login", "processed": True} # Extend for custom processing class UserDataProcessor(JSONProcessor): def process(self, input_data): input_data["user_role"] = "admin" if input_data["user"] == "john_doe" else "user" return super().process(input_data) custom_processor = UserDataProcessor() result = custom_processor.process({"user": "jane_smith"}) # Result: {"user": "jane_smith", "action": "login", "user_role": "user", "processed": True}
2. CLI Mode (Standalone Script)
Run the script directly to handle command-line inputs:
- Read from stdin, output to stdout:
echo '{"product": "laptop", "price": 999}' | python template.py - Read from file, write to output file:
python template.py -f input.json -o processed_output.json - Read from string parameter:
python template.py -s '{"task": "complete", "status": "in_progress"}'
3. Error Handling
The template includes basic guardrails for common issues:
- Invalid JSON input (prints error to stderr and exits with code 1)
- Missing input files (clear error message for users)
You can easily add more exception handling for edge cases specific to your use case.
Customization Tips
- Replace the
processmethod inJSONProcessorwith your actual business logic (data transformation, validation, etc.) - Add more CLI arguments via
argparseif you need flags for specific processing modes - Adjust JSON serialization settings (like
indent,sort_keys) inwrite_outputto match your formatting preferences
内容的提问来源于stack exchange,提问作者leonard vertighel
相关产品推荐
相关产品推荐

