How to run multiple commands in system, exec or shell_exec?
I'm trying to run shell command like this from php:
ls -a | grep mydir
But php only uses the first command. Is there any way to force php to pass the whole string to the shell?
(I don't care 开发者_运维问答about the output)
http://www.php.net/manual/en/function.proc-open.php
First open ls -a
read the output, store it in a var, then open grep mydir
write the output that you have stored from ls -a
then read again the new output.
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;
?>
If you want the output from the command, then you probably want the popen() function instead:
http://php.net/manual/en/function.popen.php
You can use
$output = shell_exec('ls -a | grep mydir');
Documentation for shell_exec
The answer:
PLEASE avoid extensive solutions for such trivial things. Here it is the solution: *as it would be so long to do it in php, then do it in python (using subprocess.Popen in python would take three lines), and then call python's script from php.
It's about seven lines in the end, and the problem ends up solved:
Script in python, we'll call it 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
how to call the python script from php:
system("pyshellforphp.py "ls | grep something");
精彩评论