0

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.

Jess
  • 186
  • 3
  • 13
  • You have a dilemma, when executing on python version < 3, the print operation is a builtin function and the parenthesis are not appropriate, however to compile for python 3 + the parenthesis are necessary to avoid compiler error. So if you remove the parenthesis, from the print, you will compile for python 2, but fail for python 3. If you leave the print statement as is, you will compile for python 3 but fail for python 2 – itprorh66 Apr 21 '21 at 14:05
  • Right. I don't need backwards compatibility with python2. I need to either: 1) exit gracefully if the user runs this in python2 instead of python3 (i.e. on our servers, they type `python myscript.py` instead of `python3 myscript.py`), or 2) forcefully switch to python3 if the user tries to run it in python2. Is either one possible? – Jess Apr 21 '21 at 14:27

1 Answers1

1

This looks like it might be similar to what you are trying to do.

I want my Python script to detect the version and quit gracefully in case of a mismatch

Shawn

Shawn Taylor
  • 270
  • 2
  • 4
  • 11
  • So could I add the shebang line `#!/usr/bin/env python3` and force it to open in python3? I'm not worried about supporting python2. It just would be nice if it could exit gracefully if someone accidentally runs it in python2. The shebang line might prevent that from happening altogether? EDIT: Nope. Editing that shebang line doesn't work. – Jess Apr 21 '21 at 14:21