14

I am faced with a unique situation, slightly trivial but painful.

I need to use Python 2.6.6 because NLTK is not ported to Python 3 (that's what I could gather).

In a different code(which am working concurrently), there is a collections counter function which is available only in Python 3 but not in Python 2.6.6.

So, each time I switch between the two codes, I need to install & uninstall the versions. That's such a waste of time.

Any suggestions on how I specify which version I want to use?

alvas
  • 115,346
  • 109
  • 446
  • 738
Learnerbeaver
  • 391
  • 2
  • 4
  • 12
  • 1
    Just install multiple versions. – David Heffernan May 05 '12 at 17:35
  • Python 2 and 3 can be installed side-by-side. Why do you need to uninstall and reinstall? – Mark Byers May 05 '12 at 17:36
  • 1
    WIndows. Yes it can be installed side-by-side. But, may be its a dumb question - how do i invoke the appropriate version (shell) from a python code ? When I say run module, it always runs on 3.0 which throws an error for nltk. – Learnerbeaver May 05 '12 at 17:38
  • just set back the path. You can use different python on window easily – Thai Tran May 05 '12 at 17:46
  • Not a unique situation. I'm using a package (pdfminer) that requires 2.x, but I need 3.0 for other projects. This is a useful question, thanks for posting it. – LarsH Dec 19 '13 at 22:01
  • The required `collections.Counter` is available also in Python 2.7 that was new in July 2010. Much more reasons can be currently for using Python 3. Upgrade from 2.6 to 2.7 is high recommended on Windows and 2.7, but on Linux it would require to keep also the old 2.6 because some system packages usually depend on it. Multiple versions are relative easy and are accessible by `python` (v2), `python3` or `python2.7` etc. There is no reason for uninstallation. Current answers are not too obsoleted, but the platform Windows/Linux of bounty is very importand for answer relevancy. – hynekcer Mar 28 '14 at 12:48
  • possible duplicate of [How to run different python versions in cmd](http://stackoverflow.com/questions/20786478/how-to-run-different-python-versions-in-cmd) – ridermansb Apr 02 '15 at 18:52

15 Answers15

20

Install Python 3

Python 3.3 and higher put a py.exe into the windows folder. [link] This executable is used to determine the python version with the first line of the file:

#!/usr/bin/python2.7

will be executed with Python 2.7. You must install the Python 3 version after you installed the other Python versions.

Additional ressources: https://docs.python.org/3/using/windows.html#customization

pywin https://pypi.python.org/pypi/pywin

Old Solution

I guess you use windows. I solved this problem with a hack:

Every time I start python on windows a python.bat will be used. This starts a python.py that analyses the file for the header after #! for the python version.

To start example.py I type into the console

python example.py

but it could also be started per klick.

this is my python file C:\bin\python.py

#!/usr/bin/env python2
import sys
import os
args = sys.argv
if len(args) <= 1:
    # no arguments
    # start python console
    i = os.system('C:\bin\python2.bat' + " ".join(args[1:]))
    if type(i) != int:
        i = 0
    exit(i)

def analyse(filename, default = ''):
    '''=> '2', '3', default '''
    try:
        f = open(filename)
    except IOError:
        # file not found
        return default
    firstLine = f.readline()
    if firstLine.startswith('#!'):
        if 'python2' in firstLine:
            return '2'
        if 'python3' in firstLine:
            return '3'
        i = firstLine.find(' ')
        if i != -1:
            # analyse from end of path on
            in2 = '2' in firstLine[i:]
            in3 = '3' in firstLine[i:]
            if in2 and not in3:
                return '2'
            if in3 and not in2:
                return '3'
        else:
            # analyse path
            in2 = '2' in firstLine
            in3 = '3' in firstLine
            if in2 and not in3:
                return '2'
            if in3 and not in2:
                return '3'
    return default



no = analyse(args[1], default = '2')
if args[1][-1:] == 'w':
    # python win
    cmd = 'C:\bin\pythonw%s.bat'
else:
    cmd = 'C:\bin\python%s.bat'
i = os.system(cmd % no + ' ' + " ".join(args[1:]))

if type(i) != int:
    i = 0
exit(i)

This is the C:\bin\python.bat file

@echo off
C:\bin\python2 C:\bin\python.py %*
rem this may also work:
rem C:\bin\python.py %*

and in every file you start you have to put either

#!/bin/env/python3

or

#!/bin/env/python2

default is python2

Then I added those files to the folder:

C:\bin\python2.bat

@echo off
C:\python27\python.exe %*

C:\bin\pythonw2.bat

@echo off
C:\python27\pythonw.exe %*

C:\python3.bat

@echo off
C:\python32\pythonw.exe %*

C:\bin\pythonw3.bat

@echo off
C:\python32\pythonw.exe %*

If you are using python26 instead if python27 then you need to change

C:\python27 

to

C:\python26

and so on. Same with python not using python 32.

You may also want to start python files per klick

then do this:

klick right on a .py file -> open with -> select C:\bin\python.bat

If you get problems contact me or leave a comment.

Community
  • 1
  • 1
User
  • 14,131
  • 2
  • 40
  • 59
10

You simply install multiple versions in separate directories, and then you run the python program with the Python version you want to use. Like so:

C:\Python26\Python.exe thescript.py

Or similar.

What virtualenv does is that it gives you many separate "virtual" installations of the same python version. That's a completely different issue, and hence it will not help you in any way.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
  • virtualenv can also work with different Python versions, so that when you have a virtualenv active, `python` points to the Python version of that virtualenv. So it's not completely irrelevant, although it's probably overkill. – Thomas K May 05 '12 at 20:10
  • 1
    @ThomasK: Yeah, but that doesn't solve his problem, and it's not necessary to solve his problem. It is as relevant as coffee. It's a nice addition, but doesn't actually solve anything. – Lennart Regebro May 06 '12 at 06:51
  • If you do this, does the python that you run know to look in the appropriate folder for packages etc.? Or will Python 2.6 look in C:\Python33\Scripts because that's what's in my PATH? – LarsH Dec 19 '13 at 22:03
  • 1
    @LarsH: It knows. No, it will not look for modules in your PATH. It will look in your PYTHONPATH, so don't set it globally. – Lennart Regebro Dec 19 '13 at 22:41
6

For those using windows, if you're not averse to using PowerShell, you can install python 2 and 3 separately as mentioned in other answers. Then you can do this:

Set-Alias python27 [some path]\python27\python.exe 
Set-Alias python33 [some path]\python33\python.exe

To create an alias for running each version.

Keeping aliases around is described in this link: https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_aliases#saving-aliases

In order to successfully load the profile that that link would have you create, you may need to change your execution policy.

Set-ExecutionPolicy RemoteSigned

should do the trick, but if you want to know more about execution policies you may want to follow this link: https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_execution_policies

J. Titus
  • 9,535
  • 1
  • 32
  • 45
James Brown
  • 383
  • 4
  • 7
  • For cmd.exe, use [doskey.com](http://technet.microsoft.com/en-us/library/bb490894.aspx) (it's really a PE exe, not DOS com). The Windows console supports aliases associated with the image name of each attached process. You can load aliases from a file using doskey's `/macrofile` option. E.g., the file's `[cmd.exe]` section could have the line `python3=C:\Python34\python.exe $*`. Add the doskey command to a cmd script loaded from the `AutoRun` value in `HKCU\Software\Microsoft\Command Processor`. You could also add a `[python.exe]` section for aliases in interactive mode. – Eryk Sun Mar 26 '14 at 22:38
5

Use virtualenv, which allows you to create dynamic python environments. Check out python's page here.

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

Related answered question on installing packages inside virtualenv on windows (as opposed to system-wide) Can I install Python windows packages into virtualenvs?

Community
  • 1
  • 1
Bryan
  • 6,682
  • 2
  • 17
  • 21
2

Use Pythonbrew, its super easy to install, and allows you to very easily install, and switch between, or temporarily use different python versions safely.

Once pythonbrew is installed:

#to install new python versions is as simple as:
pythonbrew install 2.7.2 3.2
#to use a particular version in the current shell:
pythonbrew use 3.2
#to uninstall:
pythonbrew uninstall 2.7.2
fraxel
  • 34,470
  • 11
  • 98
  • 102
1

You should look into virtualenv. I got to know about it from this blog post, which talks about pip and fabric, also very useful tools for the Python developer.

Joseph Victor Zammit
  • 14,760
  • 10
  • 76
  • 102
1

This page has an implementation of collections.Counter that works for Python 2.6:

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1

not sure this is what you want, but I used to live with this for a long time http://www.portablepython.com/

Thai Tran
  • 9,815
  • 7
  • 43
  • 64
1

The OP request is a little outdated, especially now that NLTK does have a py3.x port. see Install nltk 3.0 on Ubuntu 13.10 using tar.gz download

Here's how you can get python3 to work with NLTK.

$ sudo apt-get install python3-pip
$ sudo pip3 install pyyaml
$ wget http://www.nltk.org/nltk3-alpha/nltk-3.0a3.tar.gz
$ tar -xzvf nltk-3.0a3.tar.gz
$ cd nltk-3.0a3/
$ sudo python3 setup.py install
$ python3
>>> import nltk
>>> from nltk.corpus import brown
>>> print(brown.sents()[0])
['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', 'Friday', 'an', 'investigation', 'of', "Atlanta's", 'recent', 'primary', 'election', 'produced', '``', 'no', 'evidence', "''", 'that', 'any', 'irregularities', 'took', 'place', '.']
Community
  • 1
  • 1
alvas
  • 115,346
  • 109
  • 446
  • 738
0

I do use at least 3 or 4 versions of Python on my machines (Windows). The installers from http://python.org/ automatically placed them in:

c:\Python26
c:\Python27
c:\Python32

and

c:\Python24

on one machine. I mostly use Python 2.7 because some applications use wxPython and also for the older console code. This python.exe was not renamed. By the way, the Python 2.7 also supports collections.Counter.

The c:\Python26 and c:\Python24 are not included in my PATH. In c:\Python32\, the exe was renamed to py.exe. This way, python some.py starts Python 2.7, and py another.py starts Python 3.2.

pepr
  • 20,112
  • 15
  • 76
  • 139
0

You can specify the version you want in the shebang line. I just ran into this when a VM my Ops guy set up had Python 2.6 in /usr/bin/python2.6, and I needed 2.7 for a few features. He installed it for me at /usr/bin/python2.7.

My old shebang:

#!/usr/bin/env python

stopped working, because /usr/bin/python was a link to /usr/bin/python2.6. What wound up fixing the problem, and working across Windows, Linux, and OSX, was changing the shebang to:

#!/usr/bin/env python2.7

It should work for any version, I believe.

Chris Doggett
  • 19,959
  • 4
  • 61
  • 86
0

If you're talking about shell, as in linux, if you install python 3, you can invoke it separately with the python3 command. Python 2 is just invoked using python.

At least this is my experience with Ubuntu-like systems, I haven't used other Linux environments.

I realize this question is almost a year old, but NLTK has been ported to Python 3 (or at least that was true as of writing this).

0

Take a look on WinPython, a nice portable/installable python distribution for Windows.

Portable: preconfigured, it should run out of the box on any machine under Windows (without any requirement) and the folder containing WinPython can be moved to any location (local, network or removable drive) with most of the application settings

Flexible: one can install (or should I write "use" as it's portable) as many WinPython versions as necessary (like isolated and self-consistent environments), even if those versions are running different versions of Python (2.7, 3.3) or different architectures (32bit or 64bit) on the same machine

It also allows you to register and unregister easily a given python version as the system default one.

But even working as portable, you can make a shortcut of the python executable and put it somewhere in your path. Just name the shortcuts of different versions different names. Then you can just use:

python_3_64bit_shortcut your_program.py
Community
  • 1
  • 1
ReneSac
  • 521
  • 3
  • 9
0

You can use py launcher, that is installed with python distributable:

py -2    # default python 2
py -2.7  # specifically python 2.7
py -3    # default python 3
py -3.7  # specifically python 3.7

If you need to execute a script with a specific version you can do following:

py -3.7 my_script.py
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
0

Simplest solution : Rename the file in where your path is locations e.g: enter image description here