我有以下代码可以在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()

08-19 20:39