在 Python 2.6 中是否有跨平台获取 temp
目录路径的方法?
例如,在 Linux 下为 /tmp
,而在 XP 下为 C:\Documents and settings\[user]\Application settings\Temp
。
那将是 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 按此顺序排列。作为最后的手段,当前工作目录。
这应该做你想要的:
print tempfile.gettempdir()
对我来说,在我的 Windows 机器上,我得到:
c:\temp
在我的 Linux 机器上,我得到:
/tmp
我用:
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'
;这是我并不总是想要的。
for ((i=0;i<20;i++)) do;./testTempDir.py&;echo $!;done
中执行此操作。你会看到 20 ≠ 进程 ID 和 20 倍相同的 TMPDIR
最简单的方法,基于@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()
mkdtemp()
的更明确、更灵活的版本。
为什么会有这么多复杂的答案?
我只是用这个
(os.getenv("TEMP") if os.name=="nt" else "/tmp") + os.path.sep + "tempfilename.tmp"
/var/folders/<garbage/here>
而不是/tmp
中,因为这就是$TMPDIR
的设置方式。请参阅here。tempfile.gettempdir()
解析为C:\users\user\AppData\Local\Temp
。不幸的是,漫长的道路。