从PHP运行venv Python脚本

从PHP运行venv Python脚本,php,python,Php,Python,我正在运行许多来自PHP的python脚本。我的php脚本模板如下所示: <?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 = escapeshellar

我正在运行许多来自PHP的python脚本。我的php脚本模板如下所示:

<?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;

理想情况下,您应该使用
api
,这是最佳实践。但是如果您没有可用的
API
,您可以使用
pipe

可以像此函数一样使用:
exec\u command($command)
其中,
$command=$command。" " . $args

下面是代码:

<?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;

?>

要真正运行venv,您需要在shell中执行三个步骤:

  • 更改为项目根目录
  • venv/bin/activate
  • 运行
    python路径/to/script
  • 前提条件您已经为项目准备了虚拟环境


    您可以将这三个步骤组合成一个bash脚本,并从PHP调用此脚本。

    请解释“但它不工作”的含义。这意味着Python脚本不运行。您是否收到错误消息?如果是,哪一个?谢谢你的回复。我正在尝试,但它抛出了。@Yethrosh,请删除该函数并直接使用该函数的代码。我确信这不是因为我每天都使用这个函数exec_command()。你能按照你说的更新上面的代码吗?:)@Yethrosh,请尝试更新的解决方案,如果它有助于您接受答案。不,它不适用于虚拟环境。是的,此方法有效,但不接受$args变量。有什么建议吗?我相信您可以访问您调用的bash脚本中的$args变量。但是bash脚本不是我的领域。应该很容易查到。也许这就是答案:找出哪个部分不起作用!您不能接收脚本中的参数吗?它在外壳上工作吗?那么,它能在PHP中工作吗?是的,它能在shell中完美地工作,但在PHP中不能。$args变量似乎不起作用。