PHP中shell_exec调用Praat脚本未等待执行完成且无法捕获完整输出
问题描述
使用PHP的shell_exec调用Praat脚本时,函数未等待脚本执行完成就返回,导致获取的输出不完整。例如执行输出"hello world"的脚本,$output_string仅包含"h"。直接在终端运行对应命令正常,用var_dump($output_string)能看到完整输出,但error_log只打印"h"。
最小复现示例
Praat脚本
writeInfoLine:"hello world"
PHP代码
$output_string = shell_exec("\"path_to_praat.exe\" --run \"path_to_script\""); error_log($output_string);
解决方案
1. 清理输出中的特殊字符
error_log可能因输出包含不可见控制字符而截断内容,可先过滤掉非打印字符:
$output_string = shell_exec("\"path_to_praat.exe\" --run \"path_to_script\""); // 保留所有可打印字符 $cleaned_output = preg_replace('/[^[:print:]]/', '', $output_string); error_log($cleaned_output);
2. 改用exec捕获完整输出
exec支持通过数组捕获完整输出行,再拼接成字符串,避免部分截断问题:
$output_lines = []; exec("\"path_to_praat.exe\" --run \"path_to_script\"", $output_lines); $output_string = implode(PHP_EOL, $output_lines); error_log($output_string);
3. 统一输出编码
Praat的输出编码可能与PHP环境不一致,转换为统一编码后再写入日志:
$output_string = shell_exec("\"path_to_praat.exe\" --run \"path_to_script\""); // 自动识别原编码并转换为UTF-8 $output_string = mb_convert_encoding($output_string, 'UTF-8', 'auto'); error_log($output_string);
内容的提问来源于stack exchange,提问作者hweh
相关产品推荐
相关产品推荐

