4

Related: Is there a standard way to make sure a python script will be interpreted by python2 and not python3?

Apparently not all distros ship with a python3 symlink, either. #!/usr/bin/env python3 causes a no-such-file-or-directory error. What shebang line should I use if my script requires any version of Python 3?

Community
  • 1
  • 1
Blacklight Shining
  • 1,468
  • 2
  • 11
  • 28
  • 1
    You may need some convoluted logic to autodetect the correct interpreter in pathological cases, and a shebang is an extremely limited (and somewhat platform-dependent) tool; probably, you're better off writing a script that calls the correct interpreter passing your `.py` file to it (basically, the second answer in the linked question). – Matteo Italia Oct 28 '13 at 01:13
  • @MatteoItalia So, what…should I search all the directories in `$PATH` for executables matching `python3*`, and use the first one I find? – Blacklight Shining Oct 28 '13 at 01:16
  • I don't know what is the best way, I'm just saying that the shebang probably won't suffice. – Matteo Italia Oct 28 '13 at 01:21

1 Answers1

2
import sys
try:
   assert sys.version_info[0] == 3
except:
   print "ERROR NOT PYTHON 3!"
   sys.exit()
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • I don't think this is what OP is expecting, he want to assure a python script to be runned with python3 not with python2. What your code does is to check the version already being used and print a simple error. – Christian Tapia Oct 28 '13 at 01:55
  • 2
    @Christian If I do `python2 myscript.py`, no amount of code *inside* the script is going to change what executable called it. Unless the OP wants to write a shell script wrapper that always calls the correct version of python, this is probably the best bet. – SethMMorton Oct 28 '13 at 02:22
  • @SethMMorton [I'm probably going to](http://stackoverflow.com/questions/19625768#comment29136206_19625768) [end up going that way](http://stackoverflow.com/questions/19625768#comment29136245_19625768), yes. You could actually look around a bit for a `python3*` and `exec()` it if you find it, rather than simply `exit()`ing. That's transparent to the user. – Blacklight Shining Oct 28 '13 at 03:04
  • no assert always works ... you dont need to assert it ... you can just check it if you would rather – Joran Beasley Oct 28 '13 at 04:38