在Python2.6中,有没有一种跨平台的方法来获取temp
目录的路径?
例如,在Linux下是/tmp
,而在XP C:\Documents and settings\[user]\Application settings\Temp
下是。
发布于 2009-05-11 12:27:31
这应该是您想要的结果:
print tempfile.gettempdir()
对于我在我的Windows机器上,我得到:
c:\temp
在我的Linux机器上,我得到了:
/tmp
发布于 2017-04-15 03:51:38
我使用:
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'
;我并不总是想要这个值。
发布于 2016-05-11 04:04:21
最简单的方法,基于@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)
这类似于谷歌浏览器和Linux systemd
等应用程序所做的事情。他们只是使用更短的十六进制哈希和应用程序特定的前缀来“广告”他们的存在。
https://stackoverflow.com/questions/847850
复制相似问题