在macOS上用Python生成FFmpeg日志文件遇错误,求排查解决
问题原因
你错误地将Shell的重定向符号2>作为命令参数传给了FFmpeg。在subprocess.Popen的列表参数模式下(默认shell=False),每个列表元素都会被当作独立的命令参数,FFmpeg会把2>当成一个输出文件路径,自然找不到对应的输出格式,从而报错。
解决方案
推荐使用subprocess的标准错误重定向功能,无需依赖Shell,更安全且避免特殊字符解析问题:
import os import subprocess def create_error_logfile(videoinput): log_file_path = videoinput + ".log" cmds = [ "/applications/ffmpeg", "-v", "error", "-i", videoinput, "-f", "null", "-" ] # 打开日志文件,将FFmpeg的标准错误输出写入其中 with open(log_file_path, 'w') as log_file: subprocess.Popen(cmds, stderr=log_file).wait() # 假设input_path已定义 for root, directories, files in os.walk(input_path): for video in files: videoinput = os.path.join(root, video) create_error_logfile(videoinput)
如果你一定要用Shell重定向(不推荐,存在安全风险,比如文件名含特殊字符时可能出错),可以开启shell=True并将命令拼接为字符串:
import os import subprocess def create_error_logfile(videoinput): log_file = videoinput + ".log" # 用单引号包裹路径,避免空格等特殊字符导致的解析错误 cmd_str = f"/applications/ffmpeg -v error -i '{videoinput}' -f null - 2> '{log_file}'" subprocess.Popen(cmd_str, shell=True).wait() for root, directories, files in os.walk(input_path): for video in files: videoinput = os.path.join(root, video) create_error_logfile(videoinput)
内容的提问来源于stack exchange,提问作者Tobias
相关产品推荐
相关产品推荐

