I am struggling with a weird issue. I have a Python script that is accessed from a page via PHP and returns a JSON object with about 20 variables. All of them work all of the time except one that always returns an empty value. Directly running the Python script on the server returns a value every time, but php never sees it. I have tried output as a string, as an int, and even a string combined with a preset value. The posted code has only two shown, most of the functional values are omitted for length. ("cpul" is the one not working.)
PythonScript.py:
#!/usr/bin/python2.7
import os, json
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
tmp = (1.8 * float(res.replace("temp=","").replace("'C\n",""))) + 32
return(tmp)
# Return % of CPU used by user as a character string
def getCPUuse():
val = str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip(\
)[2:4])
return(val)
result = {'cput': CPU_temp, 'cpul': CPU_usage}
print json.dumps(result)
OUTPUT FROM SSH TERMINAL: {"cpul": "9", "cput": 106.16000000000001}
phpScript.php just passes the result on to the browser:
<?php
session_start();
try {
$result = exec('/usr/bin/python /scripts/PyhtonScript.py');
echo $result;
} catch (Exception $e) {
echo '{"res" : "ERROR", "msg" : "Caught exception: ' . $e->getMessage() . '"}';
}
?>
OUTPUT FROM BROWSER: {"cpul": "", "cput": 106.16000000000001}
If I change PythonScript.py 'result' to say:
result = {'cput': CPU_temp, 'cpul': 'foo'}
OUTPUT FROM BROWSER: {"cpul": "foo", "cput": 106.16000000000001}
and if I change PythonScript.py 'result' to say:
result = {'cput': CPU_temp, 'cpul': 'foo' + CPU_usage}
OUTPUT FROM BROWSER: {"cpul": "foo", "cput": 106.16000000000001}
If I modify the function to output an int rather than a string I get the same results without the quotes:
OUTPUT FROM SSH TERMINAL: {"cpul": 9, "cput": 106.16000000000001}
OUTPUT FROM BROWSER: {"cpul": "", "cput": 106.16000000000001}
The value is a percentage, so I would love to multiply it by 100 before sending, but if I modify the function as:
def getCPUuse():
val = str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip(\
))
mod = int(val) * 100
return(mod)
OUTPUT FROM SSH TERMINAL: {"cpul": 90, "cput": 106.16000000000001}
OUTPUT FROM BROWSER: Nothing, blank screen
APACHE2/error.log:
Traceback (most recent call last):
File "/var/www/html/assets/scripts/info_lkp.py", line 49, in <module>
CPU_usage = getCPUuse()
File "/var/www/html/assets/scripts/info_lkp.py", line 29, in getCPUuse
mod2 = int(mod)*10
ValueError: invalid literal for int() with base 10: ''
'unknown': I need something more specific.
Any idea what I am missing before I run out of hair to pull out? As stated, posted code is truncated to remove unrelated working similar functions and their associated outputs.