1

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.

asked Feb 6, 2017 at 14:29
3

2 Answers 2

0

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.

answered Feb 6, 2017 at 14:34
Sign up to request clarification or add additional context in comments.

1 Comment

Sure but how can I use shell_exec() to call multiple scripts simultaneously?
0

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 !

answered Feb 28, 2024 at 12:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.