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

使用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 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
    ];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建