繁体   English   中英

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

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

我有一个 python 脚本和一个 PHP 脚本,我需要的是通过 PHP 执行 python 脚本,并且应该将 python 代码的返回值返回给 PHP。这是我的代码

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

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

 ?>

我使用提交按钮通过另一个 php 脚本执行此操作

这是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)

我得到的结果是

返回值是:

没有任何价值。请帮忙。提前谢谢。 :)

最后我找到了这个问题的答案。在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)

这将适合场景

而不是通过

<?php 

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

?>

请参阅从PHP运行Python脚本

暂无
暂无

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

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