繁体   English   中英

无法关闭使用 Python 临时文件模块制作的临时文件

[英]Can't close temporary files made with the Python tempfile module

我正在使用一个名为pydub的基于 ffmpeg 的模块来编辑音频文件。 我正在尝试使用模块tempfile ,但由于某种原因我无法关闭文件(它们没有被删除)。 使用上下文管理器时,它会抛出PermissionError

我尝试了什么:

此代码按预期工作,但它不会删除临时文件,也不会引发错误。

temp1, temp2 = tempfile.NamedTemporaryFile(dir='data/temp', delete=False), None
# save something to temp1
seg = AudioSegment.from_file_using_temporary_files(temp1)

if options['overlay']:
    # create new seg
    if overlay_seg:
        temp2 = tempfile.NamedTemporaryFile(dir='data/temp', delete=False)
        # save something to temp2
        overlay_seg = AudioSegment.from_file_using_temporary_files(temp2)
        seg = seg.overlay(overlay_seg)

# edit the audio more here..

final = 'data//temp//edited.mp3'
seg.export(final, bitrate=options['bitrate'], format='mp3')
await ctx.send(file=discord.File(final)) # sends the file to a Discord chat
temp1.close()
if temp2:
    temp2.close()

这将创建第一个临时文件,然后引发错误:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "<myfile>", line 153, in editaudio
    await attachment.save(temp1.name)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\message.py", line 155, in save
    with open(fp, 'wb') as f:
PermissionError: [Errno 13] Permission denied: '<base>data\\temp\\tmpnf2r68qe'
with tempfile.NamedTemporaryFile(dir='data/temp') as temp1: 
    await attachment.save(temp1.name)
    seg = AudioSegment.from_file_using_temporary_files(temp1)
    if options['overlay']:
        # create new seg
        if overlay_seg:
            with tempfile.NamedTemporaryFile(dir='data/temp') as temp2:
                # save something to temp2
                overlay_seg = AudioSegment.from_file_using_temporary_files(temp2)
                seg = seg.overlay(overlay_seg)

    # edit the audio more here..

    final = 'data//temp//edited.mp3'
    seg.export(final, bitrate=options['bitrate'], format='mp3')
    await ctx.send(file=discord.File(final)) # sends the file to a Discord chat

我不确定我在这里缺少什么

好吧,如果您使用选项delete=False创建临时文件,它们不会被删除。 这是不言自明的,但在文档中也提到过。

您的第二种方法很难调试,因为您没有提供最小的可重现示例 大概是因为您已经使用上下文管理器打开了临时文件而出现了问题。 attachment.save()可能需要一条路径,但我在网上找不到文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM