3

I have 2 versions of python installed on windows, 2.7.3 and 3.3. Some of my scripts are 2.x and some 3.x. Is there an easy way when executing these scripts from a command line to direct them to the appropriate interpreter?

1
  • 1
    Ubuntu installs aliases, python2 and python3, however you don't mention what OS or installation packages you're using. Commented Sep 30, 2012 at 21:07

3 Answers 3

9

Note: For Windows use the new Windows Python launcher (available with Python 3.3 and downloadable here for earlier releases) which recognizes Unix shell shebangs. You can read about it here.

Most Linux distributions will create python2 and python3 aliases for the installed Python 2.x and Python 3.x interpreter (if not you can just create the symbolic links yourself anywhere on your $PATH, the env command will take care of finding them), so you should just need to set the appropriate interpreter as the first line of your script:

#!/usr/bin/env python2

or

#!/usr/bin/env python3

This will direct the shell to use the appropriate interpreter, if you set the script files to be executable and just invoke them directly on the shell. E.g.:

$ chmod +x script.py
$ ./script.py
Sign up to request clarification or add additional context in comments.

3 Comments

The poster didn't mention that Windows was the OS initially. :(
Yes, but its still possible to mess with PATH and aliases, i ll give it a shot
@U2ros See my improved answer with the reference to the new Windows Python launcher. That should be the ideal solution.
2

Try this first: I am on OS X, but when I want to use Python 2.6 instead of Python 2.7 (its a numpy/scipy thing), I simply run python2.6 whatever.py to run whatever.py in Python 2.6. Try that first.

If that doesn't work, then you can use virtualenv - the virtual environment builder for Python.

http://pypi.python.org/pypi/virtualenv

I am sure there are similar alternatives, too.

1 Comment

On ubuntu, im doing exactly that ;>
1

Pedro Romano's answer is the most elegant way of doing this.

But if you don't want to download and install the Python launcher, create a batch file as described below. You can also create a shortcut, copy C:\Python27\python.exe to C:\Python27\python27.exe, etc.

I'm guessing C:\Python27 and C:\Python33 are already on your system path. If so, you can create a batch file called python2.7.bat in C:\Python27\ which contains:

C:\Python27\python.exe %1

and a similar file (e.g. python3.3.bat) in C:\Python33\

Now, you can run python2.7 script.py from anywhere in command prompt and it should work :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.