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

2

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
  • 23,210
  • 7
  • 49
  • 68
lllrnr101
  • 2,123
  • 2
  • 3
  • 14
1

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
  • 23,210
  • 7
  • 49
  • 68
Dolph
  • 47,676
  • 13
  • 60
  • 88
0

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

nipun
  • 639
  • 5
  • 11