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

Linux下提取Python脚本数值及树莓派CPU温度提取报错求助

Hey Tony, let's tackle your two questions one by one—since you're new to Raspberry Pi, I'll make sure the examples are easy to follow and explain why things work (and why you might have hit syntax errors).

1. Extracting Numeric Values from a Python Script on Linux

How you do this depends on how the Python script exposes the value:

  • If the script prints the value directly to the console
    Suppose your script sensor_reading.py outputs something like 28.7 or The current value is: 35.2. You can capture and extract the number using command-line tools:

    • For simple output (only the number):
      python3 sensor_reading.py
      
      Just capture the output directly, or store it in a variable:
      value=$(python3 sensor_reading.py)
      echo $value
      
    • For output with extra text: Use grep to isolate numbers (supports integers and decimals):
      python3 sensor_reading.py | grep -oE '[0-9]+\.?[0-9]*'
      
  • If you need to pull values from variables/functions inside the script
    If the script defines variables or functions (e.g., data.py has cpu_temp = 32.1 or def get_temp(): return 34.5), you can import it into another Python script:

    # In your main script
    import data
    
    # Extract a variable
    temp = data.cpu_temp
    print(f"Extracted temperature: {temp}")
    
    # Call a function to get the value
    temp = data.get_temp()
    print(f"Function returned temperature: {temp}")
    

    If the script can't be imported (e.g., it runs standalone logic), use the subprocess module to run it and capture output:

    import subprocess
    
    # Run the script and get output
    result = subprocess.run(["python3", "path/to/your/script.py"], capture_output=True, text=True)
    raw_output = result.stdout.strip()
    
    # Convert to numeric value (assuming output is the number)
    try:
        value = float(raw_output)
        print(f"Extracted numeric value: {value}")
    except ValueError:
        print("Error: Could not convert output to a number")
    
2. Extracting CPU Temperature from vcgencmd for if-else Logic (Raspberry Pi)

Your syntax error is almost certainly because you're trying to compare a string (the full vcgencmd output) as a number, or using bash's built-in comparison which doesn't support decimals. Let's fix this with both shell and Python examples:

Shell Script Example (Bash)

Bash can't handle floating-point comparisons natively, so we use bc for math:

# Capture the temperature output and strip extra text
# Handles cases where output is "temp= 30.5'C" or "temp=30'C"
temp=$(vcgencmd measure_temp | sed 's/temp= *//; s/'\''C//')

# Compare using bc (returns 1 if true, 0 if false)
if (( $(echo "$temp > 40.0" | bc -l) )); then
    echo "⚠️ CPU is hot! Temperature: $temp°C"
else
    echo "✅ CPU temperature is normal: $temp°C"
fi

Why this works:

  • sed 's/temp= *//' removes the "temp=" prefix (and any spaces after it)
  • s/'\''C// removes the trailing 'C
  • bc -l lets us do floating-point comparisons that bash can't handle

Python Script Example

If you're writing Python code for this, it's straightforward to parse the string:

import subprocess

# Run the vcgencmd command and get output
output = subprocess.run(["vcgencmd", "measure_temp"], capture_output=True, text=True).stdout

# Parse the numeric value
# Split on "=" to get the part after, then strip spaces and 'C'
temp_str = output.split('=')[1].strip().replace("'C", "")

# Convert to float for comparisons
try:
    temp = float(temp_str)
    if temp > 40:
        print(f"⚠️ CPU overheating! Temp: {temp}°C")
    elif temp < 20:
        print(f"❄️ CPU is cold! Temp: {temp}°C")
    else:
        print(f"✅ CPU temp is normal: {temp}°C")
except ValueError:
    print("Error: Failed to parse temperature value")

Common syntax error fixes:

  • Don't forget to remove the 'C and any spaces before converting to a number (otherwise Python will throw a ValueError)
  • In shell, never use [ $temp > 40 ]—bash treats > as a redirect, not a comparison, and can't handle decimals anyway. Use bc as shown above.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:42:48