gpt4 book ai didi

php - 获取 fastCGI 脚本中的可执行路径

转载 作者:太空宇宙 更新时间:2023-11-04 12:20:48 25 4
gpt4 key购买 nike

我的开发机器和我的服务器对于安装的不同 python 版本有不同的路径。

为了得到某个 python 可执行文件的正确路径,我做了这个方法

static function pythonPath ($version='') {
$python = $version === '' ? 'python': '';
if (preg_match('/^\d(\.?\d)?$/', $version)) {
$python = 'python'.$version;
}
return trim(shell_exec("/usr/bin/which $python 2>/dev/null"));
}

在我的开发机器上我可以做到这一点

$> php -r 'require("./class.my.php"); $path=MyClass::pythonPath("2.7"); var_dump($path); var_dump(file_exists($path));'
string(18) "/usr/bin/python2.7"
bool(true)

在服务器上我得到了这个

$> php -r 'require("./class.my.php"); $path=MyClass::pythonPath("2.7"); var_dump($path); var_dump(file_exists($path));'
string(27) "/opt/python27/bin/python2.7"
bool(true)

但是如果我在 fastCGI 上使用这个方法,which 的结果是空的(CentOS 6)。据我所知,which 搜索用户的 $PATH。这可能是我没有得到 which python2.7 的任何结果的原因,因为执行脚本的用户(我猜 httpd)的路径与帐户用户。

那么,如何在 fastCGI 脚本中找到可执行路径?

拥有的用户路径不同。 (未经测试的猜测:继续使用 which 并首先获取我的服务器帐户的完整路径变量并在 which 之前加载它)

最佳答案

在我的服务器上,脚本由“nobody”用户运行。

从脚本中打印 $PATH 将显示 /usr/bin 是为运行 fastCGI 脚本的用户设置的唯一可执行二进制文件路径。

诀窍是在执行 which 之前获取我的用户环境变量。

由于 bash 配置文件的名称和我的脚本目录可能会有所不同,因此我使用此函数来获取正确的路径。

static function getBashProfilePath () {
$bashProfilePath = '';
$userPathData = explode('/', __DIR__);
if (!isset($userPathData[1]) || !isset($userPathData[2]) || $userPathData[1] != 'home') {
return $bashProfilePath;
}

$homePath = '/'.$userPathData[1].'/'.$userPathData[2].'/';
$bashProfileFiles = array('.bash_profile', '.bashrc');

foreach ($bashProfileFiles as $file) {
if (file_exists($homePath.$file)) {
$bashProfilePath = $homePath.$file;
break;
}
}

return $bashProfilePath;
}

获取 python 二进制路径的最终实现是这样的

static function pythonPath ($version='') {
$python = $version === '' ? 'python': '';
if (preg_match('/^\d(\.?\d)?$/', $version)) {
$python = 'python'.$version;
}

$profileFilePath = self::getBashProfilePath();
return trim(shell_exec(". $profileFilePath; /usr/bin/which $python 2>/dev/null"));
}

关于php - 获取 fastCGI 脚本中的可执行路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46062140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com