You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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.py isn'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 python3 instead of python—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/except blocks help catch issues like script crashes or invalid output formatting.

内容的提问来源于stack exchange,提问作者user1670773

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:15:28