我有一个Python文件,可能必须支持Python版本<3.x和> = 3.x. 有没有办法反省Python运行时知道它正在运行的版本(例如2.6 or 3.2.x)?
您如何优雅地处理失败的未来功能导入?如果用户使用Python 2.5运行,并且我的模块中的第一个语句是:
from __future__ import print_function
Run Code Online (Sandbox Code Playgroud)
为Python 2.5编译此模块将失败,并带有:
File "__init__.py", line 1
from __future__ import print_function
SyntaxError: future feature print_function is not defined
Run Code Online (Sandbox Code Playgroud)
我想告诉用户他们需要用Python> = 2.6重新运行程序,并且可能提供一些如何操作的说明.但是,引用PEP 236:
在future_statement之前可以出现的唯一行是:
- 模块docstring(如果有的话).
- 评论.
- 空白行.
- 其他future_statements.
所以我做不了类似的事情:
import __future__
if hasattr(__future__, 'print_function'):
from __future__ import print_function
else:
raise ImportError('Python >= 2.6 is required')
Run Code Online (Sandbox Code Playgroud)
因为它产生:
File "__init__.py", line 4
from __future__ import print_function
SyntaxError: from __future__ imports must occur at the beginning of the file
Run Code Online (Sandbox Code Playgroud)
来自PEP的这个片段似乎给了内联的希望:
问:我想将future_statements包装在try/except块中,因此我可以使用不同的代码,具体取决于我正在运行的Python版本.为什么我不能?
A:对不起!try/except是一个运行时功能; future_statements主要是编译时的噱头,你的try/except在编译完成后很久就会发生.也就是说,当你尝试使用/ except时,对模块有效的语义已经完成了.由于试/除非将无法完成它看起来 像它应该做到,它只是不允许的.我们还希望保持这些特殊陈述非常容易找到和识别.
请注意,您 …
I'm trying to understand one of the answers to this question:
Cannot pass an argument to python with "#!/usr/bin/env python"
#!/bin/sh
''''exec python -u -- "$0" ${1+"$@"} # '''
Run Code Online (Sandbox Code Playgroud)
This works well, but I do not understand why it works with four ticks at the beginning of that line rather than three.
In addition, why the hash near the end of that string?
我有一个只应该用Python 3运行的脚本.我想给出一个很好的错误消息,如果用户试图用Python 2.x运行它,不应该用python2运行这个脚本
我该怎么做呢?当我尝试检查Python版本时,它仍会抛出错误,因为Python在执行我的if条件之前解析整个文件.
如果可能的话,我宁愿不再制作另一个剧本.
由于python传递使用版本3作为默认值,因此需要使用corret python解释器处理版本2代码执行.我有一个小python2项目,我用它make来配置和安装python包,所以这里是我的问题:如何在里面确定python的版本Makefile?
这是我想要使用的逻辑:if(python.version == 3)python2 some_script.py2 else python3 some_script.py3
提前致谢!