如何使用subprocess调用Python脚本并获取函数返回值Y_pred
How to Capture
mytest() Return Value via subprocess Got it, let's break down how to use the subprocess module to call your calculate.py script and capture the return value of mytest() into the returned_val variable.
Step 1: Prepare calculate.py for Output
First, you need to make your script print the result of mytest() when it's run directly—since subprocess captures a script's standard output, not direct function return values. Using JSON serialization is a safe way to handle complex return types (like lists, dictionaries) without messy parsing:
# calculate.py def mytest(): # Replace this with your actual function logic return [10, 20, 30] # Example return value if __name__ == "__main__": import json # Serialize the result to JSON and print it print(json.dumps(mytest()))
Step 2: Use subprocess to Call the Script and Parse Output
In your Python console or main script, use subprocess.run() to execute calculate.py, capture its output, and convert it back into a Python variable:
import subprocess import json try: # Run the script and capture stdout/stderr proc_result = subprocess.run( ["python", "calculate.py"], # Use "python3" instead if needed on your system capture_output=True, text=True, # Return output as string instead of raw bytes check=True # Raises an exception if the script exits with an error code ) # Parse the JSON output into a Python object returned_val = json.loads(proc_result.stdout.strip()) print(f"Captured value: {returned_val}") except subprocess.CalledProcessError as e: print(f"Error running script: {e.stderr}") except json.JSONDecodeError as e: print(f"Failed to parse output: {e}")
Quick Tips:
- Path Handling: If
calculate.pyisn't in your current working directory, replace"calculate.py"with its full absolute path (e.g.,"/home/user/projects/calculate.py"). - Python Executable: On some systems, Python 3 is called with
python3instead ofpython—adjust the command list accordingly. - Simple Return Types: If
mytest()returns a basic type like an integer or string, you can skip JSON and directly cast the output (e.g.,returned_val = int(proc_result.stdout.strip())), but JSON is more robust for complex data. - Error Handling: The
try/exceptblocks help catch issues like script crashes or invalid output formatting.
内容的提问来源于stack exchange,提问作者user1670773
相关产品推荐
相关产品推荐

