2017-09-05 81 views
0

我的开发机器和我的服务器针对不同的python版本安装了不同的路径。获取fastCGI脚本中的可执行路径

为了获得一定的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")); 
} 

在我的dev的机器,我可以做到这一点

$> 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)。 据我所阅读,在用户的$PATHwhich搜索。这可能是我没有得到任何结果which python2.7的原因,因为执行该脚本的用户(我的猜测httpd)与帐户用户的路径不相同。

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

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

回答

0

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

最终实现让蟒蛇二进制路径是这样的

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")); 
} 
相关问题