有没有标准的方法来确保 python 脚本将由 python2 而不是 python3 解释? [英] Is there a standard way to make sure a python script will be interpreted by python2 and not python3?

查看:68
本文介绍了有没有标准的方法来确保 python 脚本将由 python2 而不是 python3 解释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种标准方法可以确保 python 脚本将由 python2 而不是 python3 解释?在我的发行版中,我可以使用 #!/usr/bin/env python2 作为shebang,但似乎并非所有发行版都提供python2".我可以明确调用 python 的特定版本(例如 2.6),但这会排除没有该版本的人.

在我看来,当发行版开始将 python3 作为默认的 python 解释器时,这将越来越成为一个问题.

解决方案

在很长的过渡期内,这是一个有点混乱的问题.不幸的是,除了让 Python 脚本本身在启动后检查之外,没有万无一失的跨平台方法来保证正在调用哪个 Python 版本.许多(如果不是大多数)发布 Python 3 的发行版都确保通用 python 命令的别名默认为最新的 Python 2 版本,而 python3 的别名为最新的Python 3. 不应该鼓励那些发行版这样做.但是不能保证用户不会覆盖它.我认为在可预见的未来可用的最佳实践是让打包商、分销商和用户假设 python 指的是 Python 2,并在必要时在脚本中构建运行时检查.>

Is there a standard way to make sure a python script will be interpreted by python2 and not python3? On my distro, I can use #!/usr/bin/env python2 as the shebang, but it seems not all distros ship "python2". I could explicitly call a specific version (eg. 2.6) of python, but that would rule out people who don't have that version.

It seems to me that this is going to be increasingly a problem when distros will start putting python3 as the default python interpreter.

解决方案

This is a bit of a messy issue during what will be a very long transition time period. Unfortunately, there is no fool-proof, cross-platform way to guarantee which Python version is being invoked, other than to have the Python script itself check once started. Many, if not most, distributions that ship Python 3 are ensuring the generic python command is aliased by default to the most recent Python 2 version while python3 is aliased to the most recent Python 3. Those distributions that don't should be encouraged to do so. But there is no guarantee that a user won't override that. I think the best practice available for the foreseeable future is to for packagers, distributors, and users to assume python refers to Python 2 and, where necessary, build a run-time check into the script.

这篇关于有没有标准的方法来确保 python 脚本将由 python2 而不是 python3 解释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆