4

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

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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')

1 Comment

I marked this as the accepted answer since it hit the nail on the head, for handling the "can't find 'unicode' error" and how to proceed.
2

Use sys.version_info to check your Python version. For example:

import sys

if sys.version_info[0] == 2:
    ... stuff
else:
    ... stuff

Comments

2

You should probably look into the six library to better support the differences between Python 2 and 3.

1 Comment

Thanks Daniel Roseman. That library looks super useful. I'm gonna have to start using more, and then definitely it would work in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.