如何优雅地处理失败的未来功能(__future__)导入由于旧的解释器版本?

1,344 阅读1分钟

如何优雅地处理未来的功能导入失败?如果用户正在使用Python 2.5运行,并且我的模块中的第一个语句是:

from __future__ import print_function

为Python 2.5编译此模块将失败,并显示:

  File "__init__.py", line 1
    from __future__ import print_function
SyntaxError: future feature print_function is not defined

我想通知用户,他们需要使用Python> = 2.6重新运行该程序,并且可能会提供一些有关如何执行此操作的说明。但是,引用PEP 236:

The only lines that can appear before
a future_statement are:

    The module docstring (if any).
    Comments.
    Blank lines.
    Other future_statements.

所以我不能做像:

import __future__

if hasattr(__future__, 'print_function'):
    from __future__ import print_function
else:
    raise ImportError('Python >= 2.6 is required')

因为它产生:

  File "__init__.py", line 4
    from __future__ import print_function
SyntaxError: from __future__ imports must occur at the beginning of the file

最佳答案: “我想通知用户,他们需要使用Python> = 2.6重新运行程序,并且可能会提供一些有关如何操作的说明。 这不是一个README文件是什么?

这是你的选择。一个“wrapper”:一个Python的小blob,在运行你的目标aop之前检查环境。

文件:appwrapper.py

import sys
major, minor, micro, releaselevel, serial = sys.version_info
if (major,minor) <= (2,5):
    # provide advice on getting version 2.6 or higher.
    sys.exit(2)
import app
app.main()

什么是“直接进口”的意思。您可以检查__future__的内容。你仍然受到事实的约束,从__future__ import print_function是信息到编译器,但你可以在导入模块之前捅了一下,做了真正的工作。

import __future__, sys
if hasattr(__future__, 'print_function'): 
    # Could also check sys.version_info >= __future__. print_function.optional
    import app
    app.main()
else:
    print "instructions for upgrading"

翻译自: stackoverflow.com/questions/3…

转载注明原文:python – 如何优雅地处理失败的未来功能(future)导入由于旧的解释器版本?