如何在另一Python脚本中带参数调用csdl-to-json.py脚本
Great question! There are two common approaches to integrate your existing csdl-to-json.py script into another Python workflow—one that requires no changes to your original script, and another that’s more maintainable for long-term use. Here’s how to do both:
1. Run the Script Directly with subprocess (No Modifications Needed)
If you want to keep your original script exactly as-is, you can use Python’s built-in subprocess module to execute it just like you would from the command line. This mimics the CLI call you’re already familiar with.
Example Code:
import subprocess import os def run_csdl_conversion(input_dir, output_dir): # Define the command as a list of arguments (safer for paths with spaces) cmd = [ "python3", "csdl-to-json.py", # Make sure this path is correct relative to your main script "--input", input_dir, "--output", output_dir ] try: # Execute the command and capture output result = subprocess.run( cmd, check=True, # Raises an error if the script fails capture_output=True, text=True ) print("Conversion successful!") print("Script output:", result.stdout) except subprocess.CalledProcessError as e: print(f"Conversion failed with error: {e.stderr}") # Usage in your main script input_path = "/path/to/your/csdl/files" output_path = "/path/to/save/json/files" run_csdl_conversion(input_path, output_path)
Notes:
- If
csdl-to-json.pyisn’t in the same directory as your main script, provide the full path to it (e.g.,"/home/user/scripts/csdl-to-json.py"). - Using
check=Trueensures your main script stops and reports an error if the conversion script fails. capture_output=Truelets you access the script’s stdout/stderr for debugging.
2. Refactor for Modular Use (Better for Maintainability)
For a cleaner integration, refactor your csdl-to-json.py to separate its core logic from the command-line argument parsing. This lets you import and call its functionality directly in your main script.
Step 1: Modify csdl-to-json.py
Rewrite it to expose a reusable function:
import os # Add any other imports your conversion logic uses def convert_csdl_to_json(input_dir, output_dir): # Put all your existing conversion logic here # (the code that runs after parsing CLI arguments) print(f"Converting CSDL files from {input_dir} to JSON in {output_dir}") # ... your existing code ... # Keep the CLI functionality for standalone use if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Convert CSDL XML files to JSON") parser.add_argument("--input", required=True, help="Path to CSDL source directory") parser.add_argument("--output", required=True, help="Path to JSON output directory") args = parser.parse_args() convert_csdl_to_json(args.input, args.output)
Step 2: Call the Function from Your Main Script
Now you can import and use the function directly:
# Make sure csdl-to-json.py is in the same directory or in your Python path from csdl_to_json import convert_csdl_to_json # Usage in your main script input_path = "/path/to/your/csdl/files" output_path = "/path/to/save/json/files" try: convert_csdl_to_json(input_path, output_path) print("Conversion completed successfully!") except Exception as e: print(f"Conversion failed: {str(e)}")
Notes:
- If the scripts are in different directories, add the path to
csdl-to-json.pyto your Python path first:import sys sys.path.append("/path/to/directory/containing/csdl-to-json") from csdl_to_json import convert_csdl_to_json - This approach is better for testing and reusing the conversion logic across multiple scripts.
内容的提问来源于stack exchange,提问作者kishore

