[英]check python version(s) from within a python script and if/else based on that
Basically I'd like to know if there is a way to know what version of python a script is using from within the script? 基本上我想知道是否有办法知道脚本在脚本中使用的python版本是什么? Here's my current example of where I'd like to use it: 这是我当前想要使用它的示例:
I would like to make a python script use unicode if it is using python 2, but otherwise not use unicode. 如果使用python 2,我想让python脚本使用unicode,否则不使用unicode。 I currently have python 2.7.5 and python 3.4.0 installed, and am running my current project under python 3.4.0. 我目前安装了python 2.7.5和python 3.4.0,并在python 3.4.0下运行我当前的项目。 The following scirpt: 以下scirpt:
_base = os.path.supports_unicode_filenames and unicode or str
was returning the error: 正在返回错误:
_base = os.path.supports_unicode_filenames and unicode or str
NameError: name 'unicode' is not defined
So I changed it to this in order to get it to work: 所以我将其更改为此以使其工作:
_base = os.path.supports_unicode_filenames and str
Is there a way to change it to something to this effect: 有没有办法将其更改为此效果:
if python.version == 2:
_base = os.path.supports_unicode_filenames and unicode or str
else:
_base = os.path.supports_unicode_filenames and str
You are very close: 你非常接近:
import sys
sys.version_info
Would return: 会回来:
sys.version_info(major=2, minor=7, micro=4, releaselevel='final', serial=0)
and you can do something like this: 你可以做这样的事情:
import sys
ver = sys.version_info[0]
if ver == 2:
pass
Use sys.version_info
to check your Python version. 使用sys.version_info
检查Python版本。 For example: 例如:
import sys
if sys.version_info[0] == 2:
... stuff
else:
... stuff
您应该查看six
库以更好地支持Python 2和3之间的差异。
You could define unicode
for Python 3: 您可以为Python 3定义unicode
:
try:
unicode = unicode
except NameError: # Python 3 (or no unicode support)
unicode = str # str type is a Unicode string in Python 3
To check version, you could use sys.version
, sys.hexversion
, sys.version_info
: 要检查版本,可以使用sys.version
, sys.hexversion
, sys.version_info
:
import sys
if sys.version_info[0] < 3:
print('before Python 3 (Python 2)')
else: # Python 3
print('Python 3 or newer')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.