Would like to ask , as I am designing a webpage whereby there will be a few buttons that when press will run different python scripts.
For now I have tried a basic example by using both jquery and php to pass the command to run just a single python script first that prints out hello world in the terminal console but it isn't working. I have tried searching but could not seem to find the solution. Any help? (One of them was about using fast-cgi? anyone can shed some light on this?)
Note: -I am coding on Mac OS X and using XAMPP but will be porting this code to raspberry pi with LAMPP installation. (Hence command line and advice if differ for the two OSes will be greatly appreciated)
My code:
Below are the codes where by i create a button when on press it runs a simple python script
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>
below is the code from 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);
}
});
});
});
below is the code for py_run.php
<?php
$command = escapeshellcmd("python z_py/testPyscript.py");
$output = shell_exec($command);
echo $output;
echo "php_works";
?>
the python file:
#! /usr/bin/env python
print "hello world python script"
Edit: -I have tried executing the script directly by keying in the url path name it does't work either(it does print to echo out a random test message so it is not permission error on the file i believe.) -Regarding the php code on executing python, im not familiar with using it(i found that on the forumn(can't remember where but i tried and doesnt work), found out about exec command as well and tried it as shown below and it doesn't work either :
This is my alternative Attempt on using exec (py_run.php)
<?php
$command = "python z_py/testPyscript.py";
exec($command);
?>
SOLVED! thanks to @Shawn Mehan
The solution would be that the python file is already in the same directory as the php file, hence removing the path name solves the issue.
updated code:
<?php
$command = escapeshellcmd("/usr/bin/python testPyscript.py");
$output = shell_exec($command);
echo $output;
echo "php_works";
?>