python-daemonモジュールを使おうとしています。スクリプトを適切にデーモン化するためのdaemon.DaemonContextクラスを提供します。私は主にPython2.6以降を対象としていますが、バージョン2.4との下位互換性を維持したいと考えています。
Python 2.5はfutureからのコンテキストのインポートをサポートしていますが、Python2.4にはそのような機能はありません。withステートメントで発生したエラーをキャッチし、2.4のコンテキストを手動で開始および終了できると思いましたが、発生したSyntaxErrorをキャッチできないようです。
インタプリタのバージョンを明示的にチェックする以外に、これを達成する方法はありますか?以下は、私がやろうとしていることの要点と私が直面している問題です。実生活では、コンテキストクラスを制御できないため、元のクラスを操作せずに機能する必要があります。つまり、これらのアイデアは好きではありません。
Python2.4がpython-daemonを実行できないかどうかは気にしないでください。少なくとも、エラーをキャッチしてフォールバックなどを実装できるようにしたいと思います。
助けてくれてありがとう。
#!/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)