首页 > 解决方案 > 如何通过管道连接到变量

问题描述

我想将 *.mka 内部的附件通过管道传输到变量而不是文件。

将附件保存到 *.txt 文件如下所示(并且有效):

import io
import subprocess
import sys, os
import soundfile as sf

full_path = os.path.realpath(__file__)
path, filex = os.path.split(full_path)

fname = 'my_own_soundfile.mka'
fullpath = path + '\\' + fname
pathffmpeg = 'C:/FFmpeg/bin/ffmpeg.exe'

command = [pathffmpeg, "-dump_attachment:t:0",
           "C:\folder\\attachment.txt",
           "-i", fullpath] # This one works

proc = subprocess.run(command, stdout=subprocess.PIPE)

这个命令是我尝试管道附件,但是这不起作用:

command = [pathffmpeg, "-dump_attachment:t:0",
           "-f", "PIPE:0",
           "-i", fullpath]

我能做些什么来完成这项工作?

标签: pythonpython-3.xffmpeg

解决方案


对于管道标准输出内容,将输出文件名参数替换为“管道:”

  • 子进程命令("pipe:1""pipe:"):

     command = [pathffmpeg, "-dump_attachment:t:0",
        "pipe:1",
        "-i", fullpath]
    
  • 如需阅读sdtout内容,.stdout请在运行命令后添加:

     attachment = subprocess.run(command, stdout=subprocess.PIPE).stdout
    

结果格式为字节数组。


这是一个完整的代码示例:

import subprocess

fname = 'my_own_soundfile.mka'

# For piping stdout content, replace output file name argument with "pipe:".
command = ["ffmpeg", "-dump_attachment:t:0", "pipe:", "-i", fname]

# Execute FFmpeg as subprocess and read from stdout pipe (attachment is "bytes array").
attachment = subprocess.run(command, stdout=subprocess.PIPE).stdout

attachment_str = attachment.decode("utf-8")  # Convert from bytes array to string (converting to string is optional).

推荐阅读