3

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.

fragilewindows
  • 1,394
  • 1
  • 15
  • 26
Chris
  • 133
  • 1
  • 10

1 Answers1

0

This is a Python error

When you multiply it by 100 before sending it, in your python script, error happens there.

And value is being lost, well, not because of the PHP. It's because your python script does not return valid JSON.

Read about this error here ValueError: invalid literal for int() with base 10: ''

Community
  • 1
  • 1
Bogdan Burym
  • 5,482
  • 2
  • 27
  • 46
  • I understand that the log is saying that.. What I don't understand is why running ./PythonScript.py returns a value fine via ssh terminal, but not when run through the php script. The error is indicating that the value "9" present from the command line is not present through php. – Chris Aug 01 '16 at 17:56
  • Well, this is the question of your python's script logic. Hope you understand that when you run python script via shell it is bein executed from one user. When you run pythonn script from php script, web process user is used. This may affect the result in your case, maybe. Anyway, without more details we can not help you. – Bogdan Burym Aug 01 '16 at 18:09
  • I do understand that. I originally thought it may be an issue of permissions but the cpu temp function is the same command with the output parsed differently. If that works then the permission should be there, right? I can't imagine the output is parsed differently per user? I will try to just output the full content and see what happens. – Chris Aug 01 '16 at 18:14
  • Make an experiment. Determine what is your web user name. Let's assume he is www-data. Run "sudo -u www-data ./python_script" and check the output. Is it what you expect to see or there are some unexpected values? – Bogdan Burym Aug 01 '16 at 18:17
  • Ok.. you are correct. Running the script from cli as ./PythonScript.py works as intended. Running as sudo -u www-data ./PythonScript.py produces the error from the log. That value should be produced by the line: val = str(os.popen("top n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip(\ )[2:4]) If I run top n1 | awk '/Cpu\(s\):/ {print $2}' I get the desired result, and if I run sudo -u www-data top n1 | awk '/Cpu\(s\):/ {print $2}' I also get the result. But running from the script I dont.. EDIT: I apologize.. not sure how to format in comments – Chris Aug 01 '16 at 19:05
  • Well, you need to fix your script now – Bogdan Burym Aug 01 '16 at 19:38
  • I am very confused how the user running this script is effecting the output.. I got it working by changing where it is converted to another var: `val = os.popen("top n1 | awk '/Cpu\(s\):/ {print $2}'") mod = float(val.readline().strip("\n")) * 100` but now the cpu temp function wont work when it used to be fine. – Chris Aug 01 '16 at 20:06
  • You do not understand why running the script from different user changes the things? Output of `top` can be different for different users. So, your script needs to parse different returned values in this 2 cases. – Bogdan Burym Aug 01 '16 at 20:09
  • I dont understand how running it as either user produces the same output, but modifying that output works in a single line command for one but the other requires two steps. I also dont understand how editing one function killed the output of a completely unrelated function that was working previously.. Now works from command line normally, but not as www-data, where before fixing the other one it produced the correct output when executed as either user. – Chris Aug 01 '16 at 20:30