Python无法使用tempfi设置墙纸

2024-04-26 04:57:33 发布

您现在位置:Python中文网/ 问答频道 /正文

代码:

import urllib.request
import tempfile
import shutil
import ctypes

SPI_SETDESKWALLPAPER = 20
with urllib.request.urlopen('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png') as response, tempfile.NamedTemporaryFile() as f:
    shutil.copyfileobj(response, f)
    ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, f.name, 0)

但是,如果您使用tempfile.NamedTemporaryFile(delete=False),它可以工作。你知道吗

文档状态:

If delete is true (the default), the file is deleted as soon as it is closed.

在我的原始代码中,只有在退出with语句体并自动关闭之后,文件才会被删除。那为什么SPI_SETDESKWALLPAPER不起作用呢?你知道吗


Tags: 代码importspiisresponserequestaswith
2条回答

我发现了问题:

首先,需要更改fWinIni参数的值:

SPIF_UPDATEINIFILE = 0x01
SPIF_SENDCHANGE = 0x02
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, f.name, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE)

这样可以在注销后保留壁纸。你知道吗

其次,需要关闭temp文件以使SystemParametersInfoW工作。因此,delete=False是必要的。你知道吗

最后,使用os.remove(f.name)手动删除临时文件。你知道吗

您需要阅读文档中接下来的两句话,内容如下:

Under Unix, the directory entry for the file is either not created at all or is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.

相关问题 更多 >