【发布时间】:2011-03-09 00:34:21
【问题描述】:
我正在尝试从 php 运行这样的 shell 命令:
ls -a | grep mydir
但是 php 只使用第一个命令。有什么方法可以强制 php 将整个字符串传递给 shell?
(我不关心输出)
【问题讨论】:
-
PHP 不解析 shell 命令以去除内容。你的代码是什么样的?
标签: php shell command-line exec
我正在尝试从 php 运行这样的 shell 命令:
ls -a | grep mydir
但是 php 只使用第一个命令。有什么方法可以强制 php 将整个字符串传递给 shell?
(我不关心输出)
【问题讨论】:
标签: php shell command-line exec
【讨论】:
答案:
请避免为此类琐碎的事情提供广泛的解决方案。这是解决方案: *因为在php中会很长,然后在python中进行(在python中使用subprocess.Popen需要三行),然后从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");
【讨论】:
http://www.php.net/manual/en/function.proc-open.php
首先打开 ls -a 读取输出,将其存储在 var 中,然后打开 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;
?>
【讨论】:
如果您想要命令的输出,那么您可能需要 popen() 函数:
【讨论】: