3

I'm learning python now using a mac which pre-installed python 2.7.5. But I have also installed the latest 3.4.

I know how to choose which interpreter to use in command line mode, ie python vs python 3 will bring up the respective interpreter.

But if I just write a python script with this header in it "#!/usr/bin/python" and make it executable, how can I force it to use 3.4 instead of 2.7.5?

As it stands, print sys.version says:

2.7.5 (default, Aug 25 2013, 00:04:04) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)]

tshepang
  • 10,772
  • 21
  • 84
  • 127
rockhammer
  • 847
  • 1
  • 12
  • 35
  • Does this answer your question? [How do I tell a Python script to use a particular version](https://stackoverflow.com/questions/11170827/how-do-i-tell-a-python-script-to-use-a-particular-version) – ScottyBlades May 02 '20 at 03:39

4 Answers4

6

Set the shebang (script header) to the path to python3.4 which you can get using which.

For example, here's what do I have:

$ which python
/usr/bin/python
$ which python3.4
/usr/local/bin/python3.4

Then, just set the shebang appropriately:

#!/usr/local/bin/python3.4
alecxe
  • 414,977
  • 106
  • 935
  • 1,083
  • Thanks alecxe. A follow up if I may: when I do "which python3", I get "/Library/Frameworks/Python.framework/Versions/3.4/bin/python3". Does that imply when I installed it, it got put in the wrong place? Thanks a lot. – rockhammer Apr 15 '14 at 15:48
  • @rockhammer well, you can make a symbolic link to it, e.g. `sudo ln -s /Library/Frameworks/Python.framework/Versions/3.4/bin/python3 /usr/local/bin/python3`. – alecxe Apr 15 '14 at 15:54
  • Thanks, **shebang** was the key to find this: `#!/usr/bin/python3` – mrroot5 Mar 11 '19 at 22:14
3

You know, you can start python with py -specific version To run a script on interpreter with a specific version you'll just start your script with following parameters, py yourscript.py -version

Juko
  • 39
  • 2
0

You can to the Python script a first line of:

#!/usr/bin/env python3

It is better than setting the path or the exact python 3 sub version if not needed.

Tal Haham
  • 1,093
  • 8
  • 15
0

In python you can use:

py yourscript.py -version