-1

I want to write script with logic like below

if <script invoked by python3>:
   do A
elif <script invoked by python2>:
   do B

How can I achieve this?

1
  • Version checking is easy: see @Philippe's answer. But what you want to do is less easy. A full answer to your question is beyond the scope of a SO posting. Whole books have been written about it. One such is Lennart Regebro's: freetechbooks.com/… that I made grateful use of in a recent Python 2/3 migration. Commented Mar 24, 2021 at 13:02

1 Answer 1

0

You are most likely after something similar to this (refer to original question and answer):

import sys
if sys.version_info.major >=  3:
    # Python 3 code
else:
    # Python 2 code
Sign up to request clarification or add additional context in comments.

1 Comment

Note, the named components (e.g. .major) of sys.version_info were introduced in 2.7/3.1. If, for some terrible reason, you need to support 2.6 or earlier, or 3.0, you'd test if sys.version_info >= (3,):

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.