doulaozhang0238
doulaozhang0238
2016-10-11 17:53

使用PHP exec(或类似功能)时的重定向

已采纳

In Python, we can do something like this:

pattern      = "foo"
searchfile   = "/root/text"
search       = "bar"
replace      = "baz"

tempfile     = tempfile.mkstemp()[1]
grepcmd      = ["/bin/grep", "-E", pattern, searchfile]
sedcmd       = ["/bin/sed", "-E", "s/{0}/{1}/g".format(search, replace)]
with open(tempfile, "w") as temphandle:
    grep = subprocess.Popen(grepcmd, stdout=subprocess.PIPE)
    sed = subprocess.Popen(sedcmd, stdin=grep.stdout, stdout=temphandle)
    grep.stdout.close()
    sed.communicate()

You can see that the stdout from the grep command is passed as stdin to the sed command, which in turn specifies a file handle as its stdout. This is equivalent to this shell command:

grep -E foo /root/text | sed -E 's/bar/baz/g' > /tmp/whatever

I'd like to replicate this behaviour in PHP, but am not finding the equivalent native functionality. What I've been doing is to build the equivalent shell command as a long string and pass it to shell_exec() but this is messy, especially with correct use of escapeshellarg() (note escaping is not required in the above Python code.)

$pattern    = "foo";
$searchfile = "/root/text";
$search     = "bar";
$replace    = "baz";

$tempfile   = tempnam(sys_get_temp_dir(), 'asdf');
$grepcmd    = "/bin/grep -E " . escapeshellarg($pattern) . " " . escapeshellarg($searchfile);
$sedcmd     = "/bin/sed -E " . escapeshellarg("s/$search/$replace/g");
exec("$grepcmd | $sedcmd > $tempfile);

I can also run each command separately, capturing the output in a variable, and passing it to the next command but this has obvious inefficiencies.

Is there any native way to do something similar in PHP or is my current method as good as it's going to get?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douye2036 douye2036 5年前

    You can use proc_open and related functions for that.

    $descriptorSpec = [
        0 => ['pipe', 'r'], // stdin
        1 => ['pipe', 'w'], // stdout
        2 => ['pipe', 'w'], // stderr
    ];
    
    $process = proc_open($cmd, $descriptorSpec, $pipes);
    
    if (!is_resource($process)) {
        throw new Exception('Unable to start shell process.');
    }
    
    $out = stream_get_contents($pipes[1]);
    fclose($pipes[1]);
    
    $error = stream_get_contents($pipes[2]);
    fclose($pipes[2]);
    
    $status = proc_close($process);
    if ($status !== 0) {
        throw new Exception('Command ' . $cmd . ' returned code ' . $status . '. Output: ' . $error);
    }
    

    If you want to use a output from the first command, pass one of resulting pipes to stdin descriptor of the other command:

    $descriptorSpec = [
        0 => $pipes[1], // stdin
        1 => ['pipe', 'w'], // stdout
        2 => ['pipe', 'w'], // stderr
    ];
    

    If you want to redirect one of descriptors to a file, just provide a resource you get from fopen():

    $res = fopen('file.log', 'w+');
    $descriptorSpec = [
        0 => ['pipe', 'r'], // stdin
        1 => $res, // stdout
        2 => $res, // stderr
    ];
    
    点赞 评论 复制链接分享

相关推荐