Reputation: 147
I am running many python scripts from PHP. My php script template as below:
<?php
setlocale(LC_ALL, "en_US.utf8");
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
$command = escapeshellcmd("/usr/bin/python2.7 /path/to/script");
$args = escapeshellarg($_GET["title"]). " " .
escapeshellarg($_GET["user"]);
$output = shell_exec($command . " " . $args);
echo $output;
But now I need to run some python scripts which are in virtual environment.
I tried to replace /usr/bin/python2.7
with ./www/python/venv/bin/python3
, but it does not work.
So how to run it in PHP?
Upvotes: 1
Views: 1455
Reputation: 1642
Ideally You should use APIs
, that is the best practice. But if you don't have API
available you can use pipe
.
That can be used like this function: exec_command($command)
where,
$command = $command . " " . $args
Below is the code:
<?php
setlocale(LC_ALL, "en_US.utf8");
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
$command = escapeshellcmd("/usr/bin/python2.7 /path/to/script");
$args = escapeshellarg($_GET["title"]). " " .
escapeshellarg($_GET["user"]);
$command = $command . " " . $args;
$output = "";
$hd = popen($command, "r");
while(!feof($hd))
{
$output .= fread($hd, 4096);
}
pclose($hd);
echo $output;
?>
Upvotes: 1
Reputation: 2441
To really run venv you would need to do three steps in the shell:
venv/bin/activate
python path/to/script
Prerequisite you already have prepared a virtual env for the project.
You could combine this three steps into a bash script and call this script from PHP.
Upvotes: 2