怎樣在php中執行python script?
想通過php ssh到遠程伺服器,然後執行伺服器上的一個python檔案,獲得結果,然後從php中列印出來。
My Code如下:
$connection = ssh2_connect('remote-server',22);
ssh2_auth_password($connection, 'root','pwd');
$string = ssh2_exec($connection, 'python pythonfile.py; sleep 20');
stream_set_blocking($string,true);
echo stream_get_contents($string);
但是php中列印出來的是空值。
如果我把
$string = ssh2_exec($connection, 'python pythonfile.py; sleep 20')
替換為
$string = ssh2_exec($connection, 'ls -l')
則沒有問題,程式正常輸出。
遠程伺服器中的python檔案運行一般需要15秒,所以我設定了sleep 20,但還是擷取不到結果。
想問是不是代碼哪裡有錯?要怎麼改正呢?
PHP Python SSH2
分享到:
------解決方案--------------------
引用:
解決了,我把代碼又改了下
$stream = ssh2_exec($connection, 'cd DCA_automation/main/QAUtilities/Utils; python cluster_discovery.py');
stream_set_blocking($stream, true);
$string = stream_get_contents($stream);
echo $string;
不再把python結果輸出到檔案,直接讓$stream擷取,因為"In non-blocking mode an fgets() call will always return right away while in blocking mode it will wait for data to become available on the stream",所以,如果用之前的代碼的話,一旦output.txt檔案產生,哪怕結果還沒寫上去,$stream已經獲得了資料,所以stream_set_blocking()會自動終止。但如果我將python產生結果直接寫到stream上的話,結果沒有完全產生前進程會一直block。
不知道我解釋的對不對?不恰當的地方歡迎大家指正。。
沒有錯,是stream接收到shell返回的資料時,才會觸發stream返回結果,從而執行stream_get_contents