如何使用Symfony Process组件执行identify命令
问题:Symfony Process组件执行identify命令失败的解决方法
原来通过PHP exec执行identify命令可正常获取图片数据:
$cmd = "identify -quiet -verbose '{$filePath}' "; @exec($cmd, $data);
但改用Symfony Process组件时执行始终失败:
$process = new Process(['identify', "-quiet -verbose '$filePath'"]); $process->run(); // executes after the command finishes if (!$process->isSuccessful()) { throw new ProcessFailedException($process); } $data = $process->getOutput();
报错信息:
The command "'identify' '-quiet -verbose '\''/home/daniel/Web/project/web/var/assets/177713 - file.jpg'\'''" failed. Exit Code: 1(General error) Working directory: / Output: ================ Error Output: ================ identify-im6.q16: unrecognized option `-quiet -verbose '/home/daniel/Web/project/web/var/assets/177713 - file.jpg'' @ error/identify.c/IdentifyImageCommand/790
解决方法
错误根源是Process组件的参数数组格式错误:你把-quiet、-verbose和文件路径打包成了一个数组元素,导致它们被识别成单个未知选项,而非三个独立参数。
正确写法是将每个命令参数(包括选项、文件路径)拆分为数组的独立元素,且无需手动添加引号(Process会自动处理路径中的空格等特殊字符):
use Symfony\Component\Process\Process; use Symfony\Component\Process\Exception\ProcessFailedException; $process = new Process([ 'identify', '-quiet', '-verbose', $filePath ]); $process->run(); if (!$process->isSuccessful()) { throw new ProcessFailedException($process); } // 若需要和exec返回的数组格式一致,可将输出按行分割 $data = explode(PHP_EOL, trim($process->getOutput()));
内容的提问来源于stack exchange,提问作者Daniel Częstki
相关产品推荐
相关产品推荐

