How to run multiple commands in system, exec or shell_exec?

前端 未结 4 1024
小鲜肉
小鲜肉 2021-01-23 00:05

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 p

相关标签:
4条回答
  • 2021-01-23 00:46

    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;
    ?>
    
    0 讨论(0)
  • 2021-01-23 00:50

    If you want the output from the command, then you probably want the popen() function instead:

    http://php.net/manual/en/function.popen.php

    0 讨论(0)
  • 2021-01-23 00:50

    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");
    
    0 讨论(0)
  • 2021-01-23 00:55

    shell_exec

    0 讨论(0)
提交回复
热议问题