我試圖像這樣從PHP運行shell命令:如何在系統,exec或shell_exec中運行多個命令?
ls -a | grep mydir
但是PHP只使用第一個命令。有沒有辦法強制PHP將整個字符串傳遞給shell?
(我不關心輸出)
我試圖像這樣從PHP運行shell命令:如何在系統,exec或shell_exec中運行多個命令?
ls -a | grep mydir
但是PHP只使用第一個命令。有沒有辦法強制PHP將整個字符串傳遞給shell?
(我不關心輸出)
如果你想從該命令的輸出,那麼你可能要代替POPEN()函數:
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;
?>
答案:
請避免這樣的小事廣泛的解決方案。這是它的解決方案: *因爲它會很長時間在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");
PHP不解析shell命令去除東西。你的代碼是什麼樣的? – 2010-06-28 07:56:39