Python 捕获子进程输出 [英] Python capture subprocess output
问题描述
我正在研究一个从音频流中学习的 tensorflow 项目.我正在使用子进程模块(带有 Popen
)和 FFMPEG 从 mp3 中读取音频数据.我使用 Popen()
成功打开了音频文件,并且可以通过 stdout
打印输出.但是,我似乎无法捕捉到它.
I'm working on a tensorflow project that learns from an audio stream. I'm using the subprocess module (with Popen
) and FFMPEG to read in the audio data from an mp3. I successfully open the audio file with Popen()
and I can print the output through stdout
. However, I can't seem to capture it.
我已经尝试了 read()
和 communicate()
I have tried both read()
and communicate()
我正在学习教程 这里
read()
不返回任何内容,communicate()
抛出错误:AttributeError: 'file' object has no attribute 'communicate'
read()
simply returns nothing and communicate()
throws the error: 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)
推荐答案
Popen 对象已与 stdout 通信:
pipe.communicate(str(88200*4))
还要通过标准输出捕获标准错误:
To also capture stderr through stdout:
pipe = sp.Popen(command, stdout=sp.PIPE, stderr=sp.STDOUT, stdin=sp.PIPE)
raw_audio, _ = pipe.communicate(str(88200*4).encode())
print(raw_audio)
这篇关于Python 捕获子进程输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!