问题
I have the following code which runs perfectly on Python 2.6.6:
import tempfile
with tempfile.NamedTemporaryFile() as scriptfile:
scriptfile.write(<variablename>)
scriptfile.flush()
subprocess.call(['/bin/bash', scriptfile.name])
However, when I try to run it on Python 2.4.3, I get the following error:
File "<stdin>", line 2
with tempfile.NamedTemporaryFile() as scriptfile
^
SyntaxError: invalid syntax
Is there a change in syntax in Python 2.4.3?
回答1:
Python 2.4 does not support the with
statement. So you just need to open and close the scriptfile
manually.
scriptfile = tempfile.NamedTemporaryFile()
# whatever you need to do with `scriptfile`
scriptfile.close()
回答2:
The with-statement is available only since Python 2.5 using from __future__ import with_statement
and it is enabled by default since Python 2.6.
To emulate its behaviour, you could use try/finally
:
#!/usr/bin/env python2.4
import subprocess
import tempfile
scriptfile = tempfile.NamedTemporaryFile()
try:
scriptfile.write(<variablename>)
scriptfile.flush()
subprocess.call(['/bin/bash', scriptfile.name])
finally:
scriptfile.close()
btw, you could avoid creating a file on disk by passing the script via a pipe:
from subprocess import Popen, PIPE
p = Popen('/bin/bash', stdin=PIPE)
p.communicate(<variablename>)
There are some differences but it might work as is in your case.
来源:https://stackoverflow.com/questions/18651456/tempfile-syntax-in-python-2-4-3