Check for Python version in script before functions are evaluated

I thought this post would answer this question, but the solution doesn't seem to work for me. My script is not compatible with Python 2, and I need it to exit gracefully if it is run with Python 2. It doesn't because python evaluates all the functions before running any code, regardless of where the code is placed.

Here's what I have:

import os, sys, re, argparse
import pandas as pd

if sys.version_info[0] < 3:
print("Please run this script using python 3 or higher")
sys.exit(1)

def get_samples(filename):
try:
    summary_table = pd.read_csv(filename, sep='\t')
except Exception:
    print(f"Could not import {filename} using Pandas")
    sys.exit(1)
return(summary_table['sample'])

#more functions 

def main():
    #some code here

if '__name__' == __main__:
    main()

When I test run the script in Python 2.7, the script fails at the print line (the first incompatibility location):

/usr/bin/python elims_push.py -d Run_2021.04.16-10.36.20_M947-21-010
File "myscript.py", line 43
print(f"Could not import {filename} using Pandas")

Incidentally, the except statement for the pandas import statement also doesn't work. I wanted a clean way to exit if the import breaks. That's obviously not the point of this post, but I welcome suggestions if you happen to have them.

1 answer