Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch between python 2.7 to python 3 from command line?

I'm trying to find the best way to switch between the two python compilers, 2.7 to 3.3. I ran the python script from the cmd like this:

python ex1.py

Where do I set the "python" environment in the window's environment variable to point to either python 3.3 or 2.7?

I am wondering if there is an easy way to switch between the two versions from the cmd line?

like image 483
JPC Avatar asked Aug 05 '13 12:08

JPC


People also ask

How do I run python 3 from command line?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!


4 Answers

No need for "tricks". Python 3.3 comes with PyLauncher "py.exe", installs it in the path, and registers it as the ".py" extension handler. With it, a special comment at the top of a script tells the launcher which version of Python to run:

#!python2
print "hello"

Or

#!python3
print("hello")

From the command line:

py -3 hello.py

Or

py -2 hello.py

py hello.py by itself will choose the latest Python installed, or consult the PY_PYTHON environment variable, e.g. set PY_PYTHON=3.6.

See Python Launcher for Windows

like image 170
Mark Tolonen Avatar answered Oct 19 '22 12:10

Mark Tolonen


For Windows 7, I just rename the python.exe from the Python 3 folder to python3.exe and add the path into the environment variables. Using that, I can execute python test_script.py and the script runs with Python 2.7 and when I do python3 test_script.py, it runs the script in Python 3.

To add Python 3 to the environment variables, follow these steps -

  1. Right Click on My Computer and go to Properties.
  2. Go to Advanced System Settings.
  3. Click on Environment Variables and edit PATH and add the path to your Python 3 installation directory.

For example,

enter image description here

like image 38
Sukrit Kalra Avatar answered Oct 19 '22 13:10

Sukrit Kalra


In case you have both python 2 and 3 in your path, you can move up the Python27 folder in your path, so it search and executes python 2 first.

like image 3
Philip L Avatar answered Oct 19 '22 12:10

Philip L


They are 3 ways you can achieve this using the py command (py-launcher) in python 3, virtual environment or configuring your default python system path. For illustration purpose, you may see tutorial https://www.youtube.com/watch?v=ynDlb0n27cw&t=38s

like image 2
Timothy Mugayi Avatar answered Oct 19 '22 11:10

Timothy Mugayi