MoviePy VideoFileClip 实例没有属性"reader"



我已经就此问题搜索了几天,但没有找到解决方案。我有一个大脚本(我正在尝试连接大量视频,~100-500),这就是为什么我收到错误"打开的文件太多"的原因。阅读Zulko对其他问题的回应,我看到有必要像这样手动删除每个VideoFileClip实例:

del clip.reader
del clip

面临的问题是,我有一个简单的hello_world尝试执行此操作,但得到错误VideoFileClip instance has no attribute 'reader'代码如下:

from moviepy.editor import *
rel_path = "main.py"
file_path="hello_world.mp4"
newVideo = VideoFileClip(file_path)
del newVideo.reader
del newVideo

我正在使用El Capitan(OS X),已经更新了MoviePy,Numpy,ImageMagick以及我根据需要看到的所有软件包,但是我仍然收到此错误。问题是我的计算机有时会冻结,因为它使用了太多内存。我目前正在连接 25 个视频的块,并尝试删除所有 25 个"打开的文件",连接接下来的 25 个,依此类推。之后,我会连接更长的视频。

请注意,如果没有 del newVideo.reader 行,我仍然会收到错误 打开的文件太多

当我尝试运行真实脚本时,如果我不添加newVideo.reader,则会出现以下错误

Traceback (most recent call last):
  File "/Users/johnpeebles/mispistachos/vines/video/reader.py", line 135, in compile_videos
    newVideo = VideoFileClip(videoPath).resize(height=finalHeight,width=finalWidth).set_position('center').set_start(currentDuration)
  File "/Library/Python/2.7/site-packages/moviepy/video/io/VideoFileClip.py", line 55, in __init__
    reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)
  File "/Library/Python/2.7/site-packages/moviepy/video/io/ffmpeg_reader.py", line 32, in __init__
    infos = ffmpeg_parse_infos(filename, print_infos, check_duration)
  File "/Library/Python/2.7/site-packages/moviepy/video/io/ffmpeg_reader.py", line 237, in ffmpeg_parse_infos
    proc = sp.Popen(cmd, **popen_params)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1223, in _execute_child
    errpipe_read, errpipe_write = self.pipe_cloexec()
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1175, in pipe_cloexec
    r, w = os.pipe()
OSError: [Errno 24] Too many open files
Error compiling videos
Exception AttributeError: "VideoFileClip instance has no attribute 'reader'" in <bound method VideoFileClip.__del__ of <moviepy.video.io.VideoFileClip.VideoFileClip instance at 0x136e46908>> ignore

根据Tynn的要求,我正在发布"真实代码"。正如我上面所解释的,我在这里做的是将视频编译成 25 个视频的块,然后将所有这些预编译的视频编译成一个大视频。我现在Too Many Files Open收到错误(如果我不添加 del clip.reader)

    for videoObject in data["videos"]:
        counter+=1
        #Download video and thumbnail
        downloader=urllib.URLopener()
        videoId = videoObject[API_VIDEO_ID]
        videoUrl = str(videoObject[API_VIDEO_URL])
        videoPath =os.path.join(file_dir, "tmp",str(videoObject[API_VIDEO_ID].replace("/",""))+'_video.mp4')
        thumbPath =os.path.join(file_dir, "tmp",str(videoObject[API_VIDEO_ID].replace("/",""))+'_thumb.jpg')
        currentVideoDimension = videoObject[API_VIDEO_DIMENSIONS]
        currentVideoWidth = currentVideoDimension[0]
        currentVideoHeight = currentVideoDimension[1]
        thumbUrl = str(videoObject[API_THUMB_URL])
        finalWidth = w*1.0
        finalHeight = h*1.0
        videoProportion = (float(currentVideoWidth)/float(currentVideoHeight))
        if currentVideoWidth >= currentVideoHeight:
            finalHeight = finalWidth/videoProportion
        else:
            finalWidth = finalHeight*videoProportion

        try:
            download(videoUrl, videoPath)
            download(thumbUrl, thumbPath)
        except Exception as e:
            print("Exception: "+str(e))
            print("Video ID: "+str(videoId))
            traceback.print_exc()
            continue
        #Create new video and update video duration's offset
        newVideo = VideoFileClip(videoPath).resize(height=finalHeight,width=finalWidth).set_position('center').set_start(currentDuration)
        #If it's not squared we append a video first
        if videoProportion != float(1):
            backgroundClip = ColorClip(size=((w,h)), col=colors.hex_to_rgb("#000")).set_position("center").set_start(currentDuration).set_duration(newVideo.duration)
            videos_and_subtitles.append(backgroundClip)
        #Append new video to videos
        videos_and_subtitles.append(newVideo)
        #Append subtitle to Subtitles
 #            newSubtitleText = max_text(videoObject[API_NAME],videoObject[API_AUTHOR])+" nn"+videoObject[API_AUTHOR]
        videoName = clean(videoObject[API_NAME])
        videoAuthor = clean(videoObject[API_AUTHOR])
        newSubtitleText = clean(max_text(videoName,videoAuthor)+" nn"+videoObject[API_AUTHOR])
        newSubtitle = ( TextClip(newSubtitleText,fontsize=70,color='white',font='Helvetica-Narrow',align='center',method='caption',size=titleDimensions).set_start(currentDuration).set_position((videoOffset+w,0)).set_duration(newVideo.duration) )
        videos_and_subtitles.append(newSubtitle)


        currentDuration+=newVideo.duration
        #Preprocess videos
        if counter%50==0 or len(data["videos"])==(counter):
            if closure_video_path != None and closure_video_path != "" and len(data["videos"])==(counter):
                newVideo = VideoFileClip(closure_video_path).resize(height=finalHeight,width=finalWidth).set_position((videoOffset,titleOffset)).set_start(currentDuration)
                videos_and_subtitles.append(newVideo)
                currentDuration+=closure_video_duration
            currentFilename=os.path.join(file_dir, "tmp",str(videoNumber)+fileName) 
            result = CompositeVideoClip(videos_and_subtitles,size=movieDimensions,bg_color=colors.hex_to_rgb(background_color)).set_duration(currentDuration).write_videofile(filename=currentFilename,preset='ultrafast',fps=24)
            del result
            preprocessedVideos.append(VideoFileClip(currentFilename))
            #Close files
            #close_files(videos_and_subtitles)
            for clip in videos_and_subtitles:
                try:
                    if not (isinstance(clip,ImageClip) or isinstance(clip,TextClip)):
                        del clip
                    else:
                        del clip
                except Exception,e:
                    print "Exception: "+str(e)
            #End Close files                        

            videos_and_subtitles = []
            videos_and_subtitles.append(left_holder)
            currentDuration = 0
            videoNumber+=1
            if (videoObject==data["videos"][-1]):
                break
        print("Next video")

    print("Compiling video")
    filepath = os.path.join(file_dir, "tmp",fileName) 
    result = concatenate_videoclips(preprocessedVideos).write_videofile(filename=filepath, preset='ultrafast')
    #result = CompositeVideoClip(videos_and_subtitles,size=movieDimensions,bg_color=(0,164,119)).set_duration(currentDuration).write_videofile(filename=directory+"/"+fileName,preset='ultrafast')
    print("Video Compiled")
    now = datetime.datetime.now()
    print("Finished at: "+str(now))
    return filepath
except Exception as e:
    print("Exception: "+str(e))
    print("Video ID: "+str(videoId))
    traceback.print_exc()
    rollbar.report_exc_info()
    return None

Zulko自己写道:

在MoviePy的下一个版本中,只需del clip就足够了。

这是在版本 0.2.2 发布之前。所以你似乎不需要做del clip.reader.

更准确地说,你不能这样做! VideoFileClip为您定义了一个执行此操作的析构函数:

def __del__(self):
  """ Close/delete the internal reader. """
  del self.reader

但是由于您已经删除了它,因此您可以得到AttributeError

VideoFileClip 实例没有属性"reader"

<bound method VideoFileClip.__del__ of <...VideoFileClip instance at 0x13..>>

我已经解决了我的问题,这个问题在 https://github.com/Zulko/moviepy 中有详细描述。

一旦你安装了ImageMagick,它将被MoviePy自动检测到,除了在Windows上!在手动安装MoviePy之前,Windows用户需要编辑moviepy/config_defaults.py以提供ImageMagick二进制文件的路径,这称为转换。它应该看起来像这样: IMAGEMAGICK_BINARY = "C:\Program Files\ImageMagick_VERSION\convert.exe" .

最新更新