2017-09-05 138 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")); 
} 
相關問題