I want to run a python file from my php code using exec
function. To do so I use command "python test.py"
and if I print "Hello World", it is showing.
For this my php code is like this:
<?php
$Data = exec("python test.py");
echo $Data;
?>
And the python code is:
print("Hello World")
Now I want to pass an input value say my name "Razin" to the file. So that it will print "Hello Razin"
.
Here is my python code
x = input()
print ("Hello "+x)
which should print Hello Razin
. And from php I catch it.
I don't want to pass arguments and use python system
to catch that. I want to make it like code judge system.
I hear about pipe and I read it. But it didn't clear my concept.
N.B: If you can also describe if there is more than 1 input then it'll be a great help.
Finally I found the solution. The best way to do so is using proc_open()
The code sample is given below.
$descriptorspec = array(
0 => array("pipe", "r"), //input pipe
1 => array("pipe", "w"), //output pipe
2 => array("pipe", "w"), //error pipe
);
//calling script with max execution time 15 second
$process = proc_open("timeout 15 python3 $FileName", $descriptorspec, $pipes);
if (is_resource($process)) {
fwrite($pipes[0], "2"); //sending 2 as input value, for multiple inputs use "2
3" for input 2 & 3 respectively
fclose($pipes[0]);
$stderr_ouput = [];
if (!feof($pipes[2])) {
// We're acting like passthru would and displaying errors as they come in.
$error_line = fgets($pipes[2]);
$stderr_ouput[] = $error_line;
}
if (!feof($pipes[1])) {
$print = fgets($pipes[1]); //getting output of the script
}
}
proc_close($process);