moviepy 权限错误

Permission error with moviepy

我正在尝试使用 moviepy 将 mp4 视频转换为 mp3 音频然后删除视频,代码如下:

import moviepy.editor as mp
#converting mp4 to mp3
clip = mp.VideoFileClip("videos/test.mp4")
clip.audio.write_audiofile("test.mp3")
del clip

#delete video file after converting
os.remove("videos/test.mp4")
print("Video Deleted")

这会产生以下错误 PermissionError: [WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用。

我知道我应该关闭 mp4 文件上的进程,以便像处理文件一样关闭它,但 del clip 不负责吗?

如果你想确保某些东西被关闭,你应该关闭它,而不是删除它并希望最好。


首先,del clip实际上并没有删除对象;它只是删除变量 clip。如果 clip 是对该对象的唯一引用,那么它就变成了垃圾。如果您使用的是 CPython,并且没有循环引用,则会立即检测到垃圾,并删除该对象。但是,如果这三个如果中的任何一个不成立,它就不会。

其次,即使您真的删除了该对象,也不能保证它会关闭。当然,这就是文件对象的工作方式,这也是管理外部资源的其他对象 应该 工作的方式,如果没有充分的理由不这样做的话,但它实际上并没有被语言强制执行——有时一个很好的理由,或者有时,库的 0.2 版本还没有开始编写所有清理代码。


事实上,从 the source 的快速浏览来看,MoviePy 似乎有 不在删除时自动关闭的充分理由:

    #    Implementation note for subclasses:
    #
    #    * Memory-based resources can be left to the garbage-collector.
    #    * However, any open files should be closed, and subprocesses should be terminated.
    #    * Be wary that shallow copies are frequently used. Closing a Clip may affect its copies.
    #    * Therefore, should NOT be called by __del__().

所以,不,del clip 不会为您关闭。


如果您查看模块文档字符串中的示例,例如 this one,它们会显式调用 close

    >>> from moviepy.editor import VideoFileClip
    >>> clip = VideoFileClip("myvideo.mp4").subclip(100,120)
    >>> clip.write_videofile("my_new_video.mp4")
    >>> clip.close()

因此,如果您希望事情被关闭,您大概也应该做同样的事情。