1

I need to detect Python version and execute code just for this version.

I want to use one file for each version of Python.

  • 1
    Related: [How do I check what version of Python is running my script?](https://stackoverflow.com/q/1093322/4518341) – wjandrea Feb 06 '21 at 03:23

3 Answers3

3

Use sys.version_info.

import sys
PY3 = sys.version_info[0] == 3
if PY3:
   # execute code for python 3
   import file_you_want_for_py3
else:
   # execute code for python 2
   import file_you_want_for_py2
wjandrea
  • 28,235
  • 9
  • 60
  • 81
lllrnr101
  • 2,288
  • 2
  • 4
  • 15
  • 1
    Python 4 will be a thing some day, so it'd be better to do `elif sys.version_info[0] == 2; import file_you_want_for_py2; else: #error` – wjandrea Feb 06 '21 at 03:09
  • this will work only for 2.0 (2000) and newer, try to find a better solution – user894319twitter Feb 07 '21 at 03:19
  • Use [`sys.version_info`][1] (since 2.0 in 2000). Proper reference is https://docs.python.org/2/library/sys.html#sys.version_info and not https://docs.python.org/3/library/sys.html#sys.version_info! – user894319twitter Mar 11 '23 at 16:57
2

If you're not sure which version of a module might be available, you can use a try/except:

try:
    import new_shiny_module as module
except ImportError:
    import old_rusty_module as module
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Dolph
  • 49,714
  • 13
  • 63
  • 88
0

the best and easiest way is to use tox like python library.

nipun
  • 672
  • 5
  • 11