I know if I want to run multiple Python scripts simultaneously I can knock up a bash file that looks like this;
#!/bin/bash
python pr1.py &
python pr2.py &
python now.py &
python loader.py &
But what if I want to do the same thing directly from PHP? It seems clunky to call a bash script from PHP which then runs the Python scripts.
-
4Possible duplicate of php execute a background processiFlo– iFlo2017年02月06日 14:31:22 +00:00Commented Feb 6, 2017 at 14:31
-
1stackoverflow.com/questions/11052162/run-bash-command-from-php & stackoverflow.com/questions/14155669/…Ari Gold– Ari Gold2017年02月06日 14:33:59 +00:00Commented Feb 6, 2017 at 14:33
-
Have you found an answer to that?remyremy– remyremy2020年07月29日 10:37:53 +00:00Commented Jul 29, 2020 at 10:37
2 Answers 2
Well, as far as that goes, it seems clunky to call a Python script from PHP, but you could try the shell_exec() function or execution operator.
1 Comment
You can use proc_open to run multiple Python scripts simultaneously using PHP. This provides more control over the process, and we can handle them independently.
<?php
$pythonScriptPathOne = 'script1.py';
$pythonScriptPathTwo = 'script2.py';
$command1 = "python $pythonScriptPathOne";
$command2 = "python $pythonScriptPathTwo";
$descriptors = [
0 => ['pipe', 'r'], // stdin
1 => ['pipe', 'w'], // stdout
2 => ['pipe', 'w'], // stderr
];
// Start the first Python script
$process1 = proc_open($command1, $descriptors, $pipes1);
if (is_resource($process1)) {
fclose($pipes1[0]);
// Start the second Python script
$process2 = proc_open($command2, $descriptors, $pipes2);
if (is_resource($process2)) {
fclose($pipes2[0]);
$output1 = stream_get_contents($pipes1[1]);
fclose($pipes1[1]);
proc_close($process1);
$output2 = stream_get_contents($pipes2[1]);
fclose($pipes2[1]);
proc_close($process2);
// Display the output
echo "Output from script1: $output1\n";
echo "Output from script2: $output2\n";
}
}
?>
?>
Insert as many if as you want according to number of python programs. This works fine for me !