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).
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 scriptsensor_reading.pyoutputs something like28.7orThe current value is: 35.2. You can capture and extract the number using command-line tools:- For simple output (only the number):
Just capture the output directly, or store it in a variable:python3 sensor_reading.pyvalue=$(python3 sensor_reading.py) echo $value - For output with extra text: Use
grepto isolate numbers (supports integers and decimals):python3 sensor_reading.py | grep -oE '[0-9]+\.?[0-9]*'
- For simple output (only the number):
If you need to pull values from variables/functions inside the script
If the script defines variables or functions (e.g.,data.pyhascpu_temp = 32.1ordef 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
subprocessmodule 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")
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 'Cbc -llets 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
'Cand any spaces before converting to a number (otherwise Python will throw aValueError) - In shell, never use
[ $temp > 40 ]—bash treats>as a redirect, not a comparison, and can't handle decimals anyway. Usebcas shown above.
内容的提问来源于stack exchange,提问作者Tony

