【问题标题】:Get an executable path within a fastCGI script在 fastCGI 脚本中获取可执行路径
【发布时间】:2018-02-14 04:08:42
【问题描述】:

我的开发机器和我的服务器对于安装的不同 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之前加载它)

【问题讨论】:

    标签: php linux path fastcgi


    【解决方案1】:

    在我的服务器上,脚本由“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"));
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      • 1970-01-01
      • 2022-07-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      相关资源
      最近更新 更多