Skip to main content
 首页 » 编程设计

Python捕获子进程输出

2025年05月04日17oomusou

我正在开发一个从音频流中学习的 tensorflow 项目。我正在使用子进程模块(使用 Popen)和 FFMPEG 从 mp3 中读取音频数据。我使用 Popen() 成功打开了音频文件,并且可以通过 stdout 打印输出。但是,我似乎无法捕捉到它。

我已经尝试了 read() 和 communicate()

我正在学习教程 here

read() 什么都不返回,communicate() 抛出错误:AttributeError: 'file' object has no attribute 'communicate'

这是我的代码:

for image_index, image in enumerate(image_files): 
  count += 1 
  image_file = os.path.join(folder, image) 
  try: 
    output_files = "output/output" + str(count) + ".png" 
    if image_file != 'train/rock/.DS_Store': 
        command = [FFMPEG_BIN, 
            '-i', image_file, 
            '-f', 's16le', 
            '-acodec', 'pcm_s16le', 
            '-ar', '44100', 
            '-ac', '2', 
            output_files] 
        pipe = sp.Popen(command, stdout=sp.PIPE) 
        print (pipe) 
        raw_audio = pipe.stdout.communicate(88200*4) 

我什么都试过了here和 here

请您参考如下方法:

Popen 对象没有stdout 通信:

pipe.communicate(str(88200*4)) 

同时通过 stdout 捕获 stderr:

 pipe = sp.Popen(command, stdout=sp.PIPE, stderr=sp.STDOUT, stdin=sp.PIPE) 
 raw_audio, _  = pipe.communicate(str(88200*4).encode()) 
 print(raw_audio)