【问题标题】:Running venv Python script from PHP从 PHP 运行 venv Python 脚本
【发布时间】:2019-05-27 22:04:41
【问题描述】:

我正在从 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;

但现在我需要在虚拟环境中运行一些 python 脚本。

我尝试将/usr/bin/python2.7 替换为./www/python/venv/bin/python3,但它不起作用。

那么如何在 PHP 中运行它呢?

【问题讨论】:

  • 请解释一下“但它不起作用”是什么意思。
  • 表示Python脚本没有运行。
  • 您是否收到错误消息?如果是,是哪一个?

标签: php python


【解决方案1】:

理想情况下,您应该使用APIs,这是最佳做法。但如果您没有可用的API,您可以使用pipe
可以这样使用:exec_command($command) where,
$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;

?>

【讨论】:

  • 感谢您的回复。我正在尝试这个,但它抛出 .
  • @Yethrosh,请删除函数并直接使用函数代码。而且我很确定这个 不是因为这个函数 exec_command() 因为我每天都使用它。
  • 你能按照你说的更新上面的代码吗? :)
  • @Yethrosh,请尝试更新的解决方案,如果对您有帮助,请接受答案。
  • 不,它不在虚拟环境中。
【解决方案2】:

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

  1. 更改为项目根目录。
  2. 来源venv/bin/activate
  3. 运行python path/to/script

先决条件您已经为项目准备了一个虚拟环境。

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

【讨论】:

  • 是的,这种方法有效,但它不需要 $args 变量。有什么建议吗?
  • 我确信您可以在您调用的 bash 脚本中访问 $args 变量。然而 bash 脚本不是我的领域。应该很容易查到。可能这就是答案:stackoverflow.com/questions/2740906/…
  • 找出哪个部分不起作用!你不能在脚本中收到参数吗?它在外壳上工作吗?那么,它是否适用于 PHP?
  • 是的,它在 shell 上完美运行,但在 php 中不行。看来 $args 变量不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
  • 2012-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多