How do I detect the Python version at runtime?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping
--
Chapters
00:00 How Do I Detect The Python Version At Runtime?
00:21 Accepted Answer Score 755
01:02 Answer 2 Score 34
01:15 Answer 3 Score 162
01:25 Answer 4 Score 18
01:56 Thank you
--
Full question
https://stackoverflow.com/questions/9079...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 755
Sure, take a look at sys.version and sys.version_info.
For example, to check that you are running Python 3.x, use
import sys
if sys.version_info[0] < 3:
raise Exception("Must be using Python 3")
Here, sys.version_info[0] is the major version number. sys.version_info[1] would give you the minor version number.
In Python 2.7 and later, the components of sys.version_info can also be accessed by name, so the major version number is sys.version_info.major.
See also How can I check for Python version in a program that uses new language features?
ANSWER 2
Score 162
Try this code, this should work:
import platform
print(platform.python_version())
ANSWER 3
Score 34
Per sys.hexversion and API and ABI Versioning:
import sys
if sys.hexversion >= 0x3000000:
print('Python 3.x hexversion %s is in use.' % hex(sys.hexversion))
ANSWER 4
Score 18
The best solution depends on how much code is incompatible. If there are a lot of places you need to support Python 2 and 3, six is the compatibility module. six.PY2 and six.PY3 are two booleans if you want to check the version.
However, a better solution than using a lot of if statements is to use six compatibility functions if possible. Hypothetically, if Python 3000 has a new syntax for next, someone could update six so your old code would still work.
import six
# OK
if six.PY2:
x = it.next() # Python 2 syntax
else:
x = next(it) # Python 3 syntax
# Better
x = six.next(it)