I'm trying to use the python-daemon module. It supplies the daemon.DaemonContext class to properly daemonize a script. Although I'm primarily targeting Python 2.6+, I'd like to maintain backwards compatibility to version 2.4.
Python 2.5 supports importing contexts from future, but Python 2.4 has no such facility. I figured I could just catch whatever error the with statement raises and enter and exit the context manually for 2.4, but I can't seem to catch the SyntaxError raised.
Is there any way to accomplish this short of explicitly checking the interpreter version? Below is the gist of what I'm trying to do and the problem I'm getting. In Real Life I don't have control of the context class, so it needs to work without mangling the original class, ie not like these ideas.
Nevermind if Python 2.4 can't run python-daemon; I'd at least like to able to catch the error and implement a fallback or something.
Thanks for helping.
#!/usr/bin/python2.4
from __future__ import with_statement
# with_statement isn't in __future__ in 2.4.
# In interactive mode this raises a SyntaxError.
# During normal execution it doesn't, but I wouldn't be able to catch it
# anyways because __future__ imports must be at the beginning of the file, so
# that point is moot.
class contextable(object):
def __enter__(self):
print('Entering context.')
return None
def __exit__(self, exc_type, exc_val, exc_tb):
print('Exiting context.')
return False
def spam():
print('Within context.')
context = contextable()
try:
with context: # This raises an uncatchable SyntaxError.
spam()
except SyntaxError, e: # This is how I would like to work around it.
context.__enter__()
try:
spam()
finally:
context.__exit__(None, None, None)