You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用subprocess获取ffprobe输出时字符串转int/float问题问询

问题根因

你遇到的报错和字符串类型无关,核心问题是subprocess返回的标准输出流是一次性可读的:

  • 第一次调用output.stdout.read()时,已经把ffprobe返回的所有内容(即'321')全部读取完毕,流的读取指针会直接移动到末尾
  • 之后所有再次调用read()的操作,都会直接返回空字符串'',你尝试将空字符串转换为int时,自然就触发了对应的报错。

修复方案

只需要把第一次读取到的输出内容提前存入变量,后续所有操作都基于这个变量执行即可,同时建议去掉输出前后可能存在的换行、空格等空白字符避免转换异常。

更简洁的推荐写法(使用subprocess.run)

import subprocess

def main():
    shell_ffprobe_frame_count = ["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_packets", "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0", "test.mkv"]
    # 直接用run方法捕获完整输出
    result = subprocess.run(
        shell_ffprobe_frame_count,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True
    )
    # 读取输出并去除首尾空白,存入变量复用
    frame_count_str = result.stdout.strip()
    
    print(frame_count_str) # 输出 321
    print(type(frame_count_str)) # 输出 <class 'str'>
    
    frame_count_int = int(frame_count_str)
    print(frame_count_int) # 输出 321
    print(type(frame_count_int)) # 输出 <class 'int'>

if __name__ == "__main__":
    main()

保留原有Popen写法的修改方案

import subprocess

def main():
    shell_ffprobe_frame_count = ["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_packets", "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0", "test.mkv"]
    output = subprocess.Popen(shell_ffprobe_frame_count, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    # 仅读取一次,存入变量复用
    frame_count_str = output.stdout.read().strip()
    
    print(frame_count_str)
    print(type(frame_count_str))
    print(int(frame_count_str))
    print(type(int(frame_count_str)))

if __name__ == "__main__":
    main()

内容的提问来源于stack exchange,提问作者Rashiq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 05:27:01