doulaozhang0238
2016-10-11 17:53
浏览 128
已采纳

使用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?

图片转代码服务由CSDN问答提供 功能建议

在Python中,我们可以这样做:

 <  code> pattern =“foo”
searchfile =“/ root / text”
search =“bar”
replace =“baz”
 
 
mpnmpfile = 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(sed​​cmd,stdin = grep.stdout,stdout = temphandle)
 grep  .stdout.close()
 sed.communicate()
   
 
 

您可以从 grep <中看到 stdout / code>命令作为 stdin 传递给 sed 命令,该命令又将文件句柄指定为 stdout 。 这相当于这个shell命令:

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

我想在PHP中复制这种行为,但我没有找到等效的本机功能。 我一直在做的是将等效的shell命令构建为长字符串并将其传递给 shell_exec(),但这很麻烦,特别是正确使用 escapeshellarg()(注意上述Python代码中不需要转义。)

  $ pattern =“foo”; 
 $ searchfile =“/ root / text”; \  n $ 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&gt; $ tempfile); 
   
 
 

我也可以 分别运行每个命令,捕获变量中的输出,并将其传递给下一个命令,但这显然效率低下。

是否有任何本机方式在PHP中执行类似操作或是我的 当前的方法和它一样好吗?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • douye2036 2016-10-11 18:10
    最佳回答

    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
    ];
    
    评论
    解决 无用
    打赏 举报