简体   繁体   中英

execute a python code from php and take the return value back to the php code example

I have a python script and a PHP script what I need is execute the python script through PHP and should get the return value of python code back to PHP.Here is my codes

<?php
$result1= passthru("python E:\naive-bayes-classifier-master\naiveBayesClassifier\return.py");

echo "return value is: $result1" . "\n";

 ?>

I execute this through another php script using a submit button

and here is the python code

def add(a, b):
   # print "ADDING %d + %d" % (a, b)
    return a + b

def subtract(a, b):
   #print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
    #print "MULTIPLYING %d * %d" % (a, b)
    return a * b

def divide(a, b):
   # print "DIVIDING %d / %d" % (a, b)
    return a / b

if __name__ == '__main__':
    divide(10,2)

the result I am getting is

return value is:

there no any value.Please help.Thank you in advance. :)

Finally I found the answer for this problem.In python code I only return the value.But It should be printed too.So here is the modified python code.Hope this will be useful to all of you.

def add(a, b):
   # print "ADDING %d + %d" % (a, b)
    return a + b

def subtract(a, b):
   #print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
    #print "MULTIPLYING %d * %d" % (a, b)
    return a * b

def divide(a, b):
   # print "DIVIDING %d / %d" % (a, b)
    return a / b

if __name__ == '__main__':

   ret= divide(10,2)
   print("ret:",ret)

this would be appropriate for scenario

instead of pass passthru

<?php 

$command = escapeshellcmd('E:\naive-bayes-classifier-master\naiveBayesClassifier\return.py');
$output = shell_exec($command);
echo $output;

?>

refer this : Running a Python script from PHP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM