简体   繁体   English

从php执行python代码并将返回值取回php代码示例

[英]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我有一个 python 脚本和一个 PHP 脚本,我需要的是通过 PHP 执行 python 脚本,并且应该将 python 代码的返回值返回给 PHP。这是我的代码

<?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我使用提交按钮通过另一个 php 脚本执行此操作

and here is the python code这是python代码

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.最后我找到了这个问题的答案。在python代码中我只返回值。但它也应该打印出来。所以这里是修改后的python代码。希望这对你们所有人有用。

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 请参阅从PHP运行Python脚本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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