如何在Python父脚本中带参数导入运行另一个Python脚本?
Hey there! Let's sort out this issue for you. The mistake you made is trying to use import like a terminal command—import is designed to load Python modules into your current script, not execute external scripts with command-line arguments. Here are two reliable solutions to get your OLED script running correctly from the parent script:
Option 1: Use subprocess to Run the Script Like a Terminal Command
If you don't want to modify the original demo_oled_v01.py script, you can use Python's built-in subprocess module to execute it exactly as you would in the terminal. This spawns a separate process to run the script with your required arguments.
Here's how to implement it in your parent script:
import subprocess # Execute the OLED script with all necessary arguments subprocess.run([ "python", "demo_oled_v01.py", "--display", "ssd1351", "--width", "128", "--height", "128", "--interface", "spi", "--gpio-data-command", "20" ])
Make sure the path to demo_oled_v01.py is correct (if it's in a different directory, use the full path instead of just the filename).
Option 2: Refactor the OLED Script to Support Module Import
A cleaner, more integrated approach is to modify demo_oled_v01.py so it can be imported as a module, then call its core logic directly with parameters. This avoids spawning a separate process and makes debugging easier.
Step 1: Update demo_oled_v01.py
Wrap the script's main functionality in a function, and keep the argument parsing only for when the script is run directly:
# Inside demo_oled_v01.py def run_oled(display, width, height, interface, gpio_data_command): # Place all your existing OLED initialization/rendering code here # Replace any references to command-line args with these function parameters # ... (your original code) ... if __name__ == "__main__": # Keep the original argument parser for direct terminal execution import argparse parser = argparse.ArgumentParser() parser.add_argument("--display", required=True) parser.add_argument("--width", type=int, required=True) parser.add_argument("--height", type=int, required=True) parser.add_argument("--interface", required=True) parser.add_argument("--gpio-data-command", type=int, required=True) args = parser.parse_args() run_oled( args.display, args.width, args.height, args.interface, args.gpio_data_command )
Step 2: Call the Function from Your Parent Script
Now you can import the module and call the run_oled function with your parameters directly:
import demo_oled_v01 # Call the OLED function with your required settings demo_oled_v01.run_oled( display="ssd1351", width=128, height=128, interface="spi", gpio_data_command=20 )
Which Option Should You Choose?
- Use
subprocessif you want to keep the original script untouched and just run it as-is. - Use the refactored module approach if you want tighter integration between scripts, better performance, and easier debugging.
内容的提问来源于stack exchange,提问作者Craver2000

