尝试使用Popen执行ffmpeg
命令时遇到一个奇怪的问题。
我有以下代码,用于在Python中执行外部命令:
from subprocess import Popen, PIPE
from datetime import datetime
class Executor(object):
@classmethod
def execute(cls, command):
"""
Executing a given command and
writing into a log file in cases where errors arise.
"""
p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate()
if p.returncode:
with open("failed_commands.log", 'a') as log:
now = datetime.now()
log.write('{}/{}/{} , {}:{}:{}\n\n'.format(now.day, now.month,
now.year, now.hour,
now.minute,
now.second))
log.write("COMMAND:\n{}\n\n".format(" ".join(command)))
log.write("OUTPUT:\n{}\n\n".format(output.decode("utf-8")))
log.write("ERRORS:\n{}\n".format(err.decode("utf-8")))
log.write('-'*40)
log.write('\n')
return ''
if not output:
output += ' '
return output
我已经使用其他命令测试了它,但是当我尝试执行ffmpeg
命令时 - 它失败了。
我试图将某些音频格式转换为mp3格式。
以下是我的命令示例:
ffmpeg -i "/path/old_song.m4a" "/path/new_song.mp3"
......就这么简单。当我在终端中运行它时工作正常,但是当我尝试使用上面的函数执行它时它会失败。 这是确切的错误:
----------------------------------------
21/9/2014 , 19:48:50
COMMAND:
ffmpeg -i "/path/old_song.m4a" "/path/new_song.mp3"
OUTPUT:
ERRORS:
ffmpeg version 2.2.3 Copyright (c) 2000-2014 the FFmpeg developers
built on Jun 9 2014 08:01:43 with gcc 4.9.0 (GCC) 20140521 (prerelease)
configuration: --prefix=/usr --disable-debug --disable-static --enable-avisynth --enable-avresample --enable-dxva2 --enable-fontconfig --enable-gnutls --enable-gpl --enable-libass --enable-libbluray --enable-libfreetype --enable-libgsm --enable-libmodplug --enable-libmp3lame --enable-libopencore_amrnb --enable-libopencore_amrwb --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librtmp --enable-libschroedinger --enable-libspeex --enable-libtheora --enable-libv4l2 --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libx265 --enable-libxvid --enable-pic --enable-postproc --enable-runtime-cpudetect --enable-shared --enable-swresample --enable-vdpau --enable-version3 --enable-x11grab
libavutil 52. 66.100 / 52. 66.100
libavcodec 55. 52.102 / 55. 52.102
libavformat 55. 33.100 / 55. 33.100
libavdevice 55. 10.100 / 55. 10.100
libavfilter 4. 2.100 / 4. 2.100
libavresample 1. 2. 0 / 1. 2. 0
libswscale 2. 5.102 / 2. 5.102
libswresample 0. 18.100 / 0. 18.100
libpostproc 52. 3.100 / 52. 3.100
"/path/old_song.m4a": No such file or directory
Conversion failed!
----------------------------------------
......正如你所能想到的那样 - 文件存在。
我认为有一些事情可以将命令传递给Popen.communicate
,但我并不确切知道。
亲切的问候,
Teodor D.
PS:我将命令传递给Executor.execute as Python
列表。
PSS:致电Executor.execute
:
def process_conversion(self):
for song in self.files_to_convert:
current_format = song.rsplit('.', 1)[-1]
old_file = '"{}{}{}"'.format(self.target_dir, os.sep, song)
new_file = '"{}{}{}"'.format(self.target_dir, os.sep,
song.replace(current_format, 'mp3'))
command = ["ffmpeg", "-i", old_file, new_file]
Executor.execute(command)
答案 0 :(得分:2)
问题是您在文件名中包含双引号。请改用:
old_file = '{}{}{}'.format(self.target_dir, os.sep, song)