在PhP不工作的情况下执行一些python脚本


Executing a few python scripts with PhP not working

想问一下,因为我正在设计一个网页,其中将有几个按钮,当按下将运行不同的python脚本。

现在我已经尝试了一个基本的例子,使用jquery和php来传递命令,首先运行一个python脚本,在终端控制台中打印出hello world,但它不工作。我试着寻找,但似乎找不到解决办法。任何帮助吗?(其中一个是关于使用快速cgi?有人能解释一下吗?)

注意:我在Mac OS X上编写代码并使用XAMPP,但将把此代码移植到安装了LAMPP的树莓派上。(因此,如果两个操作系统的命令行和建议不同,将非常感谢)

我代码:

下面是我创建按钮的代码,当按下它运行一个简单的python脚本

Main.php

<!DOCTYPE html>
<html>
<head>
 <script type="text/javascript" src="js/general_v2.js"></script>
</head>
    <body>
        <button id="button_py1" type="button">Press to test Py</button>
 </body>
 </html>
下面的代码来自general_v2.js
$(document).ready(function(){
  $('#button_py1').click(function() {
  e.preventDefault();
  $.ajax({
   type: "POST",
   url: "z_py/py_run.php",

   success: function(output_string){
    console.log("js_success");
   },
   error:function(err){
    //handle error
    alert('Error submitting form' + err);
   }
});    
});
});
下面是py_run.php 的代码
<?php
        $command = escapeshellcmd("python z_py/testPyscript.py");
        $output = shell_exec($command);
        echo $output;
        echo  "php_works";
?>

python文件

#! /usr/bin/env python
print "hello world python script"

编辑:-我已经尝试直接通过键入url路径名称来执行脚本,它也不起作用(它确实打印出随机测试消息,因此我相信它不是文件上的权限错误。)-关于执行python的php代码,我不熟悉使用它(我发现在论坛上(不记得在哪里,但我试过了,不工作),发现了关于exec命令,并尝试如下所示,它也不起作用:

这是我的替代尝试使用exec (py_run.php)

<?php
        $command = "python z_py/testPyscript.py";
        exec($command);
?>

解决!感谢@Shawn Mehan

解决方案是python文件已经与php文件在同一目录中,因此删除路径名可以解决问题。

更新代码:

<?php
        $command = escapeshellcmd("/usr/bin/python testPyscript.py");
        $output = shell_exec($command);
        echo $output;
        echo  "php_works";
?>

好吧,如果我稍微改变你的py_run.php,包括python的路径,你的代码为我工作,例如:

<?php
        $command = escapeshellcmd("/path/to/python/python z_admin_face/testPyscript.py");
        $output = shell_exec($command);
        echo $output;
        echo  "php_face2";
?>

这里不要使用escapeshellcmd。该函数用于转义参数,这样用户就不能输入foo;reboot并使系统重新启动。但是,由于您没有任何用户输入,因此您不需要它。

而不是:

$output = shell_exec("python z_admin_face/testPyscript.py");