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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)