python - python 2.4.3 中的临时文件语法

标签 python with-statement python-2.4

我有以下代码,可以在 Python 2.6.6 上完美运行:

import tempfile
with tempfile.NamedTemporaryFile() as scriptfile:
        scriptfile.write(<variablename>)
        scriptfile.flush()
        subprocess.call(['/bin/bash', scriptfile.name])

但是,当我尝试在 Python 2.4.3 上运行它时,出现以下错误:

File "<stdin>", line 2
    with tempfile.NamedTemporaryFile() as scriptfile
                ^
SyntaxError: invalid syntax

Python 2.4.3 中的语法有变化吗?

最佳答案

Python 2.4 不支持 with 语句。所以你只需要手动打开和关闭scriptfile

scriptfile = tempfile.NamedTemporaryFile()

# whatever you need to do with `scriptfile`

scriptfile.close()

关于python - python 2.4.3 中的临时文件语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18651456/

相关文章:

python - 查找数据框是否是另一个数据框的子集,同时忽略索引

python - Pyspark:dataframe describe() 和 summary() 是如何实现的

python-3.x - For/if 状态以一种方式工作,但不以另一种方式工作

javascript - With 语句的性能影响

python - 在 with_statement 中使用实例的问题

python - 使用 cPickle 在 2.4 中 pickle array.array

python - pyinstaller 不显示图像和图标

Python:如何启用除以零并返回零值?

python - 在 python 2.4 中并行化循环

python - 类型错误 : __init__() takes exactly 1 argument (3 given) pyXML