2010-06-28 198 views
2

我試圖像這樣從PHP運行shell命令:如何在系統,exec或shell_exec中運行多個命令?

ls -a | grep mydir 

但是PHP只使用第一個命令。有沒有辦法強制PHP將整個字符串傳遞給shell?

(我不關心輸出)

+0

PHP不解析shell命令去除東西。你的代碼是什麼樣的? – 2010-06-28 07:56:39

回答

2

http://www.php.net/manual/en/function.proc-open.php

首先打開ls -a讀取輸出,將其存儲在av ar,然後打開grep mydir寫入您從ls -a存儲的輸出,然後再次讀取新的輸出。

L.E:

<?php 
//ls -a | grep mydir 

$proc_ls = proc_open("ls -a", 
    array(
    array("pipe","r"), //stdin 
    array("pipe","w"), //stdout 
    array("pipe","w") //stderr 
), 
    $pipes); 

$output_ls = stream_get_contents($pipes[1]); 
fclose($pipes[0]); 
fclose($pipes[1]); 
fclose($pipes[2]); 
$return_value_ls = proc_close($proc_ls); 


$proc_grep = proc_open("grep mydir", 
    array(
    array("pipe","r"), //stdin 
    array("pipe","w"), //stdout 
    array("pipe","w") //stderr 
), 
    $pipes); 

fwrite($pipes[0], $output_ls); 
fclose($pipes[0]); 
$output_grep = stream_get_contents($pipes[1]); 

fclose($pipes[1]); 
fclose($pipes[2]); 
$return_value_grep = proc_close($proc_grep); 


print $output_grep; 
?> 
0

答案:

請避免這樣的小事廣泛的解決方案。這是它的解決方案: *因爲它會很長時間在php中完成,然後在python中執行(使用subprocess.Popen在python中將佔用三行),然後從php中調用python的腳本。

它在末端約七條線路,而問題最終得到解決:

腳本在Python中,我們把它叫做pyshellforphp.py

import subprocess 
import sys 
comando = sys.argv[1] 
obj = subprocess.Popen(comando, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) 
output, err = obj.communicate() 
print output 

如何從PHP調用python腳本:

system("pyshellforphp.py "ls | grep something"); 
相關問題