我有以下代码可以在 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 = tempfile.NamedTemporaryFile()
# whatever you need to do with `scriptfile`
scriptfile.close()
