如何从Lua向Python脚本传递运行时变量及生成的数据参数?
Hey there! Let's figure out how to pass your Lua-generated image data and other containers to a Python script using os.execute (or better alternatives for trickier cases). Here are a few practical approaches depending on your data type:
1. Passing Text/Numeric Data as Command Line Arguments
If your data is small (like file paths, metadata strings, or numbers), you can directly construct a command string in Lua that includes these as arguments for your Python script. Just make sure to handle spaces and special characters properly by wrapping arguments in quotes.
Lua Code Example
-- Assume you've generated these values local generated_image_path = "./output/my_image.png" local image_metadata = {width = 1920, height = 1080, color_mode = "RGB"} -- Encode metadata to JSON (use dkjson library or similar for reliability) local json = require("dkjson") local metadata_str = json.encode(image_metadata) -- Build the command: wrap arguments in quotes to avoid splitting on spaces local python_command = string.format('python3 your_python_script.py "%s" "%s"', generated_image_path, metadata_str) -- Execute the command local success, exit_status = os.execute(python_command) if success then print("Python script ran without issues!") else print("Oops, script failed with exit code:", exit_status) end
Corresponding Python Script
import sys import json # Grab arguments from command line image_path = sys.argv[1] metadata_json = sys.argv[2] metadata = json.loads(metadata_json) # Use the data as needed print(f"Processing image at: {image_path}") print(f"Image specs: {metadata['width']}x{metadata['height']}, {metadata['color_mode']}")
2. Handling Large/Binary Data (Like Raw Image Data)
Command line arguments have length limits, so if you're working with raw binary image data (instead of just a file path), using pipes (via io.popen in Lua) is a better approach. This lets you stream data directly to Python's standard input.
Lua Code Example (Streaming Data)
local raw_image_data = -- Your in-memory binary image data (e.g., from a generation library) local image_metadata = {dpi = 300, format = "PNG"} local json = require("dkjson") local metadata_str = json.encode(image_metadata) -- Open a pipe to write data to Python's stdin local pipe = io.popen("python3 your_python_script.py", "w") if pipe then -- First send metadata (use a newline as a separator) pipe:write(metadata_str .. "\n") -- Then send the raw binary image data pipe:write(raw_image_data) pipe:close() print("Data sent to Python successfully!") else print("Failed to establish connection with Python script") end
Python Script (Reading from Stdin)
import sys import json # Read metadata first (split by newline) metadata_json = sys.stdin.readline().strip() metadata = json.loads(metadata_json) # Read remaining data as binary image content image_data = sys.stdin.read() # Save or process the image with open("./received_image.png", "wb") as img_file: img_file.write(image_data) print(f"Saved image with DPI: {metadata['dpi']}")
Key Notes
- Escape Special Characters: Always wrap arguments in quotes when building command strings to avoid issues with spaces, slashes, or special symbols.
- JSON for Structured Data: Using JSON to encode structured metadata ensures both Lua and Python can parse it reliably without manual string parsing headaches.
- Avoid Overloading Command Line: For large datasets or binary content, pipes or temporary files are safer than command line arguments (which have OS-specific length limits).
内容的提问来源于stack exchange,提问作者omar.sayed

