补充现有的有用答案:
您可能希望编写脚本同时运行 Python 2.x 和 3.x,并且至少需要每个的版本。
例如,如果您的代码使用 argparse 模块,则您至少需要 2.7(使用 2.x Python)或至少需要 3.2(使用 3.x Python)。
下面的sn -p 实现了这样的检查;唯一需要适应不同但类似情况的是MIN_VERSION_PY2=... 和MIN_VERSION_PY3=... 分配。
如前所述:这应该放在脚本顶部,在任何其他import 语句之前。
import sys
MIN_VERSION_PY2 = (2, 7) # min. 2.x version as major, minor[, micro] tuple
MIN_VERSION_PY3 = (3, 2) # min. 3.x version
# This is generic code that uses the tuples defined above.
if (sys.version_info[0] == 2 and sys.version_info < MIN_VERSION_PY2
or
sys.version_info[0] == 3 and sys.version_info < MIN_VERSION_PY3):
sys.exit(
"ERROR: This script requires Python 2.x >= %s or Python 3.x >= %s;"
" you're running %s." % (
'.'.join(map(str, MIN_VERSION_PY2)),
'.'.join(map(str, MIN_VERSION_PY3)),
'.'.join(map(str, sys.version_info))
)
)
如果不满足版本要求,则会将以下消息打印到 stderr 并且脚本以退出代码 1 退出。
This script requires Python 2.x >= 2.7 or Python 3.x >= 3.2; you're running 2.6.2.final.0.
注意:这是对早期不必要的复杂答案的大幅改写版本,在意识到 - 感谢Arkady's helpful answer - 可以将比较运算符(如>)直接应用于元组之后。