可疑的 mktemp 使用 (S306)
源自 flake8-bandit linter。
作用
检查对 tempfile.mktemp
的使用。
为什么这不好?
tempfile.mktemp
返回一个在调用时不存在的文件路径名;然后,调用者负责创建该文件并随后使用它。这是不安全的,因为在函数返回和调用者创建文件之间的时间段内,另一个进程可能会创建具有相同名称的文件。
tempfile.mktemp
已被弃用,建议使用 tempfile.mkstemp
,它在被调用时创建文件。考虑使用 tempfile.mkstemp
代替,可以直接使用,也可以通过上下文管理器(例如 tempfile.TemporaryFile
)使用。
在 预览 中,此规则还将标记对 tempfile.mktemp
的引用。
示例
import tempfile
tmp_file = tempfile.mktemp()
with open(tmp_file, "w") as file:
file.write("Hello, world!")
建议改为