ChatGPT解决这个技术问题 Extra ChatGPT

在 Python 中获取临时目录的跨平台方法

在 Python 2.6 中是否有跨平台获取 temp 目录路径的方法?

例如,在 Linux 下为 /tmp,而在 XP 下为 C:\Documents and settings\[user]\Application settings\Temp

不是 Python 专家,但您应该使用 these 方法来创建临时文件/目录
请参阅 docs.python.org/library/tempfile.html 处的 tempfile 模块。

n
nosklo

那将是 tempfile 模块。

它具有获取临时目录的功能,并且还具有一些快捷方式来在其中创建临时文件和目录,无论是命名的还是未命名的。

例子:

import tempfile

print tempfile.gettempdir() # prints the current temporary directory

f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here

为了完整起见,根据文档,这是它搜索临时目录的方式:

由 TMPDIR 环境变量命名的目录。由 TEMP 环境变量命名的目录。由 TMP 环境变量命名的目录。特定于平台的位置:在 RiscOS 上,由 Wimp$ScrapDir 环境变量命名的目录。在 Windows 上,目录 C:\TEMP、C:\TMP、\TEMP 和 \TMP 按此顺序排列。在所有其他平台上,目录 /tmp、/var/tmp 和 /usr/tmp 按此顺序排列。作为最后的手段,当前工作目录。


对我来说,OSX 将它放在 /var/folders/<garbage/here> 而不是 /tmp 中,因为这就是 $TMPDIR 的设置方式。请参阅here
目前,在 Windows 10 上使用 python 3.6.5,tempfile.gettempdir() 解析为 C:\users\user\AppData\Local\Temp。不幸的是,漫长的道路。
R
RichieHindle

这应该做你想要的:

print tempfile.gettempdir()

对我来说,在我的 Windows 机器上,我得到:

c:\temp

在我的 Linux 机器上,我得到:

/tmp

但这不适用于 MacOS...Asclepius 的答案是 MacOS 更好的选择
A
Asclepius

我用:

from pathlib import Path
import platform
import tempfile

tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())

这是因为在 MacOS,即 Darwin 上,tempfile.gettempdir()os.getenv('TMPDIR') 返回一个值,例如 '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T';这是我并不总是想要的。


至少在这种情况下,MacOS 正确地返回了一个用户级隔离临时目录。我 99.99% 确定这是您需要的……除非您想弄乱操作系统。
@sorin 99.99% 有点牵强。我会说50%更现实。我经常使用多处理,然后我可能希望所有进程都使用相同的临时目录。
@Acumenus 确实据我所知 sorin 是对的。您认为 osx 上的 TMPDIR 对于每个进程都会有所不同的假设是错误的。 TMPDIR 是每个用户但每个会话。此位置在重新启动时被清除。如果您想说服自己尝试显示 TMPDIR 并将其保存到 testTempdir.py 的 python 代码,然后在您的终端 for ((i=0;i<20;i++)) do;./testTempDir.py&;echo $!;done 中执行此操作。你会看到 20 ≠ 进程 ID 和 20 倍相同的 TMPDIR
@StephaneGasparini,是的,但有时您需要来自不同父级(会话)的单独进程,这是跨平台的
@Asclepius TMPDIR 是一个环境变量,据我所知,它表达了 NSTemporaryDirectory 的结果。 API 文档说它是每个用户看到的 developer.apple.com/documentation/foundation/…。另见stackoverflow.com/questions/10293348/…
h
hobs

最简单的方法,基于@nosklo 的评论和answer

import tempfile
tmp = tempfile.mkdtemp()

但是如果你想手动控制目录的创建:

import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)

这样,您可以在完成后轻松清理(为了隐私、资源、安全等):

from shutil import rmtree
rmtree(tmp, ignore_errors=True)

这类似于 Google Chrome 和 Linux systemd 等应用程序所做的事情。他们只是使用较短的十六进制哈希和特定于应用程序的前缀来“宣传”他们的存在。


您应该改用 tempfile.mkdtemp()
@nosklo,这当然是一个选项,并且可以利用 tempfile 包中内置的所有稳健性,但是哈希方法允许您创建您选择的路径并将多个目录嵌套在满足您要求的目录树中。它基本上是您建议的 mkdtemp() 的更明确、更灵活的版本。
F
Freak

为什么会有这么多复杂的答案?

我只是用这个

   (os.getenv("TEMP") if os.name=="nt" else "/tmp") + os.path.sep + "tempfilename.tmp"

这比其他答案更简单吗?