Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check python version(s) from within a python script and if/else based on that

Tags:

python

unicode

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? 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. I currently have python 2.7.5 and python 3.4.0 installed, and am running my current project under python 3.4.0. The following 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
like image 867
Aaron Lelevier Avatar asked Dec 26 '22 11:12

Aaron Lelevier


2 Answers

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
like image 55
Vor Avatar answered Dec 30 '22 10:12

Vor


You could define unicode for Python 3:

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:

import sys

if sys.version_info[0] < 3:
   print('before Python 3 (Python 2)')
else: # Python 3
   print('Python 3 or newer')
like image 27
jfs Avatar answered Dec 30 '22 11:12

jfs