I have a big third-party python2.7 application, a bunch of python scripts, which is added into PATH and it requires python2.7 instead of python 3.5 which I have by default.
$ python
Python 3.5.1 (default, Mar 3 2016, 09:29:07)
[GCC 5.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
$ python2
Python 2.7.11 (default, Mar 3 2016, 11:00:04)
[GCC 5.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
I run that application as $ some_app arg1 arg2. How can make it use python2 as a temporary solution, preferably only in that single terminal window?
I don't substitute a call of that application with "python". I call it like $ some_app arg1 arg2. I don't want to change the version of python permanently or modify the source code of the application.
My favorite way: use virtualenv or pyenv
The most used tool for keeping multiple Python environments is virtualenv. I like to use a sugary wrapper around it called virtualenvwrapper.
Usually I install it using:
sudo pip install virtualenvwrapper
Then I add a line like the following one to my shell profile:
source /usr/local/bin/virtualenvwrapper.sh
Now you can make a virtual environment for each version of Python. Gosh, you can make one for each Python project!
mkvirtualenv py3
mkvirtualenv py2 --python=python2
Then you can switch temporarily to python2 by typing:
workon py2
There is another tool called pyenv that lets you easily switch between multiple versions of Python. Quoting the project readme, "It's simple, unobtrusive, and follows the UNIX tradition of single-purpose tools that do one thing well. This project was forked from rbenv and ruby-build, and modified for Python". Looks like it is getting popular.
Both are elegant, easy to use and a perfect fit for this use case (switch to a particular python version in a terminal window temporarily).
The Unix way: set $PATH
It is a best practice to write the shebang for Python scripts like:
#!/usr/bin/env python
If the 3rd-party app you are running follows this convention, you can change the PATH. For example, suppose the default python interpreter is not the one you want:
$ env python --version
Python 3.5.1
Make a local copy of the python you want to make the default temporarily (you just have to do this one time):
$ mkdir ~/local
$ mkdir ~/local/python2
$ ln -s `which python2` ~/local/python2/python
Then every time you want to make python2 the default, do:
$ export PATH=~/local/python2/:$PATH
Now the default is the version you want:
$ env python --version
Python 2.7.10
The positive karma way: if the 3rd-party app has a hardcoded path in the shebang
Perhaps the app author did not follow the best practices and hardcoded the Python path in the shebang. For example, suppose the first line of the program is:
#!/usr/bin/python
In this case, none of the previous tricks would work. Personally, I would change it to the canonical form and send a pull request to the author of the 3rd-party app.
The bossy way: change the default Python version system-wide
While this does not really answer your question - because it affects every window and avery other user in the system - I'm mentioning it for the sake of completeness.
For example, if you are using Ubuntu you can change the default python interpreter using:
$ update-alternatives --config python
Other Linux distributions probably have something like this.
Quick and dirty
The shebang just tells the shell to call the script using the given interpreter. You can override the shebang when calling the app as interpreter app:
$ python2 `which app_name`
Or:
$ python2 /path/to/app_name
You can also just edit the program and change the shebang:
#!/usr/bin/python2
Note that this would change permanently the Python interpreter for that program, it is not temporary nor restricted to a particular terminal. Worst, if the program is in the global PATH, all the other users of the system will be affected. If you want to restore the old behavior, you must undo your changes.
That said, sometimes you just don't care about doing it right, you just want to make it work.
You can make use of terminal alias. The alias will not be temporary but it will not affect your system, so you can have a short alias like:
alias pyt "/usr/bin/python2.7"
in your .bashrc file inside home directory
As the question is tagged with Linux, I assume your scripts starts with that line
#! /usr/bin/env python
This is great to allow the system to choose the current Python installation, but here your requirement is to specifically use version 2.7
So IMHO you just have to change the hashbang line to select the required version:
#! /path/to/python-2.7
If you are using Anaconda as your Python distribution, it has virtual enviroments built in. If not, use virtualenv and virtualenvwrapper as Paul recommended.
In addition I recommend autoenv. With that you can automatically change your venv depending on the folder you're in. There is one for bash and one for zsh.
Related
If I have python script which activates the virtualenv like this:
#!/path/to/venv/bin/python
How can I set variables for this script without modifying this script?
I want this environment variable to be active for all scripts which use this virtualenv.
This means modifying this script is not a solution, since there are twenty scripts, and I don't want to modify twenty scripts.
Writing a shell wrapper-script around the python scripts would work, but I would like to avoid this.
In the past I thought a custom sitecustomize.py can be used for start-up code. But Ubuntu (AFAIK the only distribution which does this) comes with its own sitecustomize.py file, with the effect that my sitecustomize.py does not get called. See https://bugs.launchpad.net/ubuntu/+source/python2.5/+bug/197219
Here are some ways how I want to use the virtualenv:
Script which gets executed via unix cron.
virtualenv in a systemd service. See: How to enable a virtualenv in a systemd service unit?
via mod_wsgi (Apache): https://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html#daemon-mode-single-application
(I have thought about this again. I guess it setting the variables is not the job of python or virtualenv. I need a unified way to set environment variables. And in my case I would like to do this without using a shell wrapper).
while writing sitecustomize.py file and changing bin/python all are feasible solutions, I would suggest another method that does not involve directly change contents inside virutalenv, by simply install a .pth file:
./venv/lib/python2.7/site-packages/_set_envs.pth
with content:
import os; os.environ['FOO'] = 'bar'
test:
$ ./venv/bin/python -c "import os; print os.getenv('FOO')"
bar
the trick is, python will load every .pth file on startup, and if there is a line starts with import, this line will be get executed, allowing inject arbitrary code.
the advantage is, you could simply write a python package to install this .pth file with setuptools, install to the virtualenv you want to change.
From what I have tried, it seems if you create a sitecustomize.py file inside the virtual environment, it will take precedence over the global sitecustomize.pyinstalled in /usr/lib/python2.7 directory. Here is what I did:
Create a sitecustomize.py in the virtual environment
$ echo "import os; os.environ['FOO'] = 'BAR'" > ~/venvs/env_test/lib/python2.7/sitecustomize.py
Verify that it is getting imported and executed when running the Python binary from the virtual environment
$ ~/venvs/env_test/bin/python
Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sitecustomize
>>> sitecustomize.__file__
'/home/abhinav/venvs/env_test/lib/python2.7/sitecustomize.py'
>>> import os
>>> os.environ['FOO']
'BAR'
>>>
Just to verify that FOO is set even without explicitly importing sitecustomize:
$ ~/venvs/env_test/bin/python
Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['FOO']
'BAR'
>>>
After trying dotenv package as well as the .pth method, I discovered they didn't work for me. So, I just modified the venv/bin/activate script, and exported the variables there.
Here's the idea.
$ cat venv/bin/activate
deactivate () {
unset FOO
unset BAR
...
}
...
export FOO='xxx'
export BAR='xxx'
Bit hackish, but should work.
Rename python link in virtual environment bin to something like python.lnk
In bin folder create file python that looks like
#!/bin/sh
export TEST='It works!'
"$0.lnk" "$#"
Make it executable
chmod +x python
Then if you run a script like
#!/work/venv/bin/python
import os
print 'Virtualenv variable TEST="{}"'.format(os.environ['TEST'])
as follows:
./myscript.py
it prints out:
Virtualenv variable TEST="It works!"
How to do in Ubuntu
The problem with Ubuntu it seems that python package comes with PYTHONNOUSERSITE as cPython compilation flag. You can find it with site module and see that site.ENABLE_USER_SITE is set to False.
Specific problem with the question
tl;dr #!/path/to/venv/bin/python is not enough to execute your virtual environment.
Although the rest of the answers seems to be correct in some contexts, the problem with the question is that he forces the execution with #!/path/to/venv/bin/python but hi is not providing any contextual virtual environment in his question, so I suppose he is not activating his virtual environment previous to run his script.
That is useless because that command usually links to your system python executable[^1] and does anything more. Also, by default you will use your system environment variables if you don't activate the virtual environment with source /path/to/venv/bin/activate or configure apache or nginx to manage your venv.
Solution for environment vars in venv
Then, is possible to add a specific line in your venv/bin/activate script that adds a environment value in bash language:
export FOO=BAR
and then activate it with source command.
[^1]: Probably you will prefer a generic #!/usr/bin/env python3 (python2 is deprecated). The environment will take properly your exectuable.
I installed both Python 2.7 and 3.4 on my computer, but now Python seems to confuse about the paths. It always shows syntax error when I run the scripts that worked before. I uninstalled both of the versions by removing them in application, and reinstall 2.7, but the problem remains the same. What should I do now?
Now I type Python in terminal:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
I tried this http://hints.binaryage.com/how-to-install-python-3-2-3-on-mac-os-x/ before I uninstall both versions but it didn't work.
If you want to understand which path variables you have set, you can type:
echo $PATH
at the command line in terminal and it'll tell you the 'path' (where it's looking when you type a command like 'python'). Another test you can do uses the 'which' command to see which file it'll pick when you type a command e.g.
which python
You can specify what you want the PATH variable to look like by editing one of several files. These are always stored in your home directory (shortcut on command line is ~ E.G. ~/myfile.txt) but there are a few file names that might be being used depending on your setup. Commonly the file names are .profile or .bash_profile, but there are others. NB: the '.' at the start of the file name means they're hidden from normal view. You can view all files in your home directory using the command:
ls -al ~
On my Mac, the file used is .bash_profile
Anyway, that'll help you see where the problem lies. As the previous answer states, often when you install both, one is given a specific name e.g. python27 or python3 or whatever.
However, the best approach is probably to get to know and then use, VirtualEnv: https://virtualenv.pypa.io/en/latest/
This lets you create a new, virtual python environment for every project. You set them up, telling them which python version to use and which libraries/packages to include, and then there are no clashes between projects. There is a stack overflow for how to tell virtualenv which python to use here: Use different Python version with virtualenv
And that brings me back to where I was. Understanding where your python files are and what they are called (e.g. python, python27, python3 etc) is necessary for this process. So hopefully the stuff at the top of my answer will help you to discover your pythons and then you can make use of VirtualEnv.
I want to upgrade python's default version i.e /usr/bin/python in Linux.
I have multiple python versions installed as
/usr/bin/python2.7
/usr/bin/python3.3
However, python command still returns python2.7
# python
Python 2.7
Type "help", "copyright", "credits" or "license" for more information.
>>>
Now, I have installed a module, which got installed in the default version 2.7.
That's why I can't use python3.3 script.py, as it returns error for missing module.
How to update this default version to 3.3?
Is there a way to install the module in /usr/bin/python3.3 as well?
Added: Module is pexpect-2.3.
Installing new python, installs by default in /usr/local/bin.
Adding this path to PATH before previous default python's path, solves the problem.
export PATH=/usr/local/bin:$PATH
# This export statement could be added to .bashrc for permanent effect.
This way old python is not messed and new one is installed.
Also, If there is already a python present in /usr/local/bin, changing symbolic link of /usr/local/bin/python to new /usr/local/bin/python3.3 solves the problem. (Python install generally only creates link when it installs in /usr/local/bin. You can do ls on /usr/local/bin/python to verify that it is link. Because python is installed as /usr/local/bin/python2.7 and then a link to this is created as below)
/usr/local/bin/python -> /usr/local/bin/python2.7
or
/usr/local/bin/python -> /usr/local/bin/python3.3
Ofcourse, path of this should be added to PATH as already mentioned above.
It's always better to never touch and mess with /usr/bin/python version, unless there is strong reason, because /usr/bin/python is generally not a link and is required by many of os modules.
The accepted answer is good though, however I have found another hack trick to this problem and I think it's pretty simple.
At the location of /usr/bin/ there are many python related files available. You can see the file python is actually a link and it points to the python2(which is pointed to python2.7).
So whenever you command python it calls the python2.7 not python3.5
The solution is to delete the original python link and make another link that points to python3.5 and make the newly link file name to python.
And you are done. :D
I had two versions of Python installed on my machine (versions 2.6 and 2.5). I want to run 2.6 for one project and 2.5 for another.
How can I specify which I want to use?
I am working on Windows XP SP2.
Running a different copy of Python is as easy as starting the correct executable. You mention that you've started a python instance, from the command line, by simply typing python.
What this does under Windows, is to trawl the %PATH% environment variable, checking for an executable, either batch file (.bat), command file (.cmd) or some other executable to run (this is controlled by the PATHEXT environment variable), that matches the name given. When it finds the correct file to run the file is being run.
Now, if you've installed two python versions 2.5 and 2.6, the path will have both of their directories in it, something like PATH=c:\python\2.5;c:\python\2.6 but Windows will stop examining the path when it finds a match.
What you really need to do is to explicitly call one or both of the applications, such as c:\python\2.5\python.exe or c:\python\2.6\python.exe.
The other alternative is to create a shortcut to the respective python.exe calling one of them python25 and the other python26; you can then simply run python25 on your command line.
Adding two more solutions to the problem:
Use pylauncher (if you have Python 3.3 or newer there's no need to install it as it comes with Python already) and either add shebang lines to your scripts;
#! c:\[path to Python 2.5]\python.exe - for scripts you want to be run with Python 2.5
#! c:\[path to Python 2.6]\python.exe - for scripts you want to be run with Python 2.6
or instead of running python command run pylauncher command (py) specyfing which version of Python you want;
py -2.6 – version 2.6
py -2 – latest installed version 2.x
py -3.4 – version 3.4
py -3 – latest installed version 3.x
Install virtualenv and create two virtualenvs;
virtualenv -p c:\[path to Python 2.5]\python.exe [path where you want to have virtualenv using Python 2.5 created]\[name of virtualenv]
virtualenv -p c:\[path to Python 2.6]\python.exe [path where you want to have virtualenv using Python 2.6 created]\[name of virtualenv]
for example
virtualenv -p c:\python2.5\python.exe c:\venvs\2.5
virtualenv -p c:\python2.6\python.exe c:\venvs\2.6
then you can activate the first and work with Python 2.5 like this
c:\venvs\2.5\activate
and when you want to switch to Python 2.6 you do
deactivate
c:\venvs\2.6\activate
From Python 3.3 on, there is the official Python launcher for Windows (http://www.python.org/dev/peps/pep-0397/). Now, you can use the #!pythonX to determine the wanted version of the interpreter also on Windows. See more details in my another comment or read the PEP 397.
Summary: The py script.py launches the Python version stated in #! or Python 2 if #! is missing. The py -3 script.py launches the Python 3.
As per #alexander you can make a set of symbolic links like below. Put them somewhere which is included in your path so they can be easily invoked
> cd c:\bin
> mklink python25.exe c:\python25\python.exe
> mklink python26.exe c:\python26\python.exe
As long as c:\bin or where ever you placed them in is in your path you can now go
> python25
For example for 3.6 version type py -3.6.
If you have also 32bit and 64bit versions, you can just type py -3.6-64 or py -3.6-32.
install python
C:\Python27
C:\Python36
environment variable
PYTHON2_HOME: C:\Python27
PYTHON3_HOME: C:\Python36
Path: %PYTHON2_HOME%;%PYTHON2_HOME%\Scripts;%PYTHON3_HOME%;%PYTHON3_HOME%\Scripts;
file rename
C:\Python27\python.exe → C:\Python27\python2.exe
C:\Python36\python.exe → C:\Python36\python3.exe
pip
python2 -m pip install package
python3 -m pip install package
I strongly recommend the pyenv-win project.
Thanks to kirankotari's work, now we have a Windows version of pyenv.
One easy way for this is that you can use
py -3.8 -m pip install virtualenv here -3.8 goes with your [version number]
After installing the virtualenv, you can create the virtual environment of your application using
py -3.8 -m virtualenv [your env name]
then cd to venv, enter activate
This would activate the python version you like.
Just change the version number to use a different python version.
When you install Python, it will not overwrite other installs of other major versions. So installing Python 2.5.x will not overwrite Python 2.6.x, although installing 2.6.6 will overwrite 2.6.5.
So you can just install it. Then you call the Python version you want. For example:
C:\Python2.5\Python.exe
for Python 2.5 on windows and
C:\Python2.6\Python.exe
for Python 2.6 on windows, or
/usr/local/bin/python-2.5
or
/usr/local/bin/python-2.6
on Windows Unix (including Linux and OS X).
When you install on Unix (including Linux and OS X) you will get a generic python command installed, which will be the last one you installed. This is mostly not a problem as most scripts will explicitly call /usr/local/bin/python2.5 or something just to protect against that. But if you don't want to do that, and you probably don't you can install it like this:
./configure
make
sudo make altinstall
Note the "altinstall" that means it will install it, but it will not replace the python command.
On Windows you don't get a global python command as far as I know so that's not an issue.
Here's a quick hack:
Go to the directory of the version of python you want to run
Right click on python.exe
Select 'Create Shortcut'
Give that shortcut a name to call by( I use p27, p33 etc.)
Move that shortcut to your home directory(C:\Users\Your name)
Open a command prompt and enter name_of_your_shortcut.lnk(I use p27.lnk)
cp c:\python27\bin\python.exe as python2.7.exe
cp c:\python34\bin\python.exe as python3.4.exe
they are all in the system path, choose the version you want to run
C:\Users\username>python2.7
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>>
C:\Users\username>python3.4
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
The easiest way to run multiple versions of python on windows is described below as follows:-
1)Download the latest versions of python from python.org/downloads by selecting the relevant version for your system.
2)Run the installer and select Add python 3.x to the path to set path automatically in python 3 (you just have to click the checkbox). For python 2 open up your python 2 installer, select whatever preferences you want but just remember to set Add python.exe to path to Will be installed on local hard drive, Now just click next and wait for the installer to finish.
3)When both the installations are complete. Right click on my computer--Go to properties--Select advanced system settings--Go to environment variables--Click on new under System variables and add a new system variable with variable name as PY_PYTHON and set this variable value to 3. Now click on OK and you should be done.
4)Now to test this open the command prompt. Once you are in there type python or py, It should open up python3.
5)Now exit out of python3 by typing exit(). Now type py -2 it should open python 2.
If none of this works then restart the computer and if the problem still persists then uninstall everything and repeat the steps.
Thanks.
This is a simple and elegant solution to easily run 2 or more different versions of python without using scripts in Windows. Whatever the version of python, it will start from the Command prompt.
I have python versions 3.6.6 and 3.9. The Environment Variable paths are normal and were automatically added when each version of python was installed.
It's best to install python using the "all users" option. This way the python will simply install to:
C:\program files\python36
C:\program files\python39
Open each of these python folders and find the python.exe file. Copy and paste the python.exe file into those same folders. Then carefully rename the copies to:
python36.exe
python39.exe
Open and edit Environment Variables. Add 4 new User Variables.
C:\Program Files\Python36\Scripts
C:\Program Files\Python36\python36.exe
C:\Program Files\Python39\Scripts
C:\Program Files\Program39\python39.exe
Save and exit Environment Variables.
Open a new Command Prompt terminal window. To run one or the other version of python, type:
python36
python39
More versions of python can easily be added by repeating the same as shown above. Elegant and simple. Done.
Using a batch file to switch, easy and efficient on windows 7. I use this:
In the environment variable dialog (C:\Windows\System32\SystemPropertiesAdvanced.exe),
In the section user variables
added %pathpython% to the path environment variable
removed any references to python pathes
In the section system variables
removed any references to python pathes
I created batch files for every python installation (exmple for 3.4 x64
Name = SetPathPython34x64 !!! ToExecuteAsAdmin.bat ;-) just to remember.
Content of the file =
Set PathPython=C:\Python36AMD64\Scripts\;C:\Python36AMD64\;C:\Tcl\bin
setx PathPython %PathPython%
To switch between versions, I execute the batch file in admin mode.
!!!!! The changes are effective for the SUBSEQUENT command prompt windows OPENED. !!!
So I have exact control on it.
let's say if we have python 3.7 and python 3.6 installed.
they are respectively stored in following folder by default.
C:\Users\name\AppData\Local\Programs\Python\Python36
C:\Users\name\AppData\Local\Programs\Python\Python37
if we want to use cmd prompt to install/run command in any of the above specific environment do this:
There should be python.exe in each of the above folder.
so when we try running any file for ex. (see image1) python hello.py. we call that respective python.exe. by default it picks lower version of file. (means in this case it will use from python 3.6 )
image
so if we want to run using python3.7. just change the .exe file name. for ex. if I change to python37.exe and i want to use python3.7 to run hello.py
I will use python37 hello.py . or if i want to use python3.7 by default i will change the python.exe filename in python3.6 folder to something else . so that it will use python3.7 each time when I use only python hello.py
Shows your installed pythons
py -0
Uses version of python to do something
py -*version*
ex.
py -3.8 venv venv
Will create virtual environment in python 3.8
Note:
python -0
or
python -3.8
doesn't work, I assume it has to be "py"
You can create different python development environments graphically from Anaconda Navigator.
I had same problem while working with different python versions so I used anaconda navigator to create different python development environments and used different python versions in each environments.
Here is the help documentation for this.
https://docs.anaconda.com/anaconda/navigator/tutorials/manage-environments/
Introduce more details based on the answer given by #Aman.
Define different environment variables for different python versions.
For example:
You have E:\python2\python.exe and E:\python3\python.exe at the same time.
Then you can set an environment variable %python2% for E:\python2\python.exe and %python2% for E:\python3\python.exe.
Finally, when you want to run python2 (or python3), you can enter %python2% (or %python3%) directly in command prompt.
Here is a solution:
First, install all versions which you want to run in your pc. https://www.python.org/
Second, create virtual environment with which python version you want to use.
"py [python_version] -m venv [vritual_environment_name]" example: "py -3.9 -m venv env"
Note: You don't need to run "pip install virtualenv"
Using the Rapid Environment Editor you can push to the top the directory of the desired Python installation. For example, to start python from the c:\Python27 directory, ensure that c:\Python27 directory is before or on top of the c:\Python36 directory in the Path environment variable. From my experience, the first python executable found in the Path environment is being executed. For example, I have MSYS2 installed with Python27 and since I've added C:\MSYS2 to the path before C:\Python36, the python.exe from the C:\MSYS2.... folder is being executed.
I thought this answer might be helpful to others having multiple versions of python and wants to use pipenv to create virtual environment.
navigate to the project directory, and run py -[python version] pip install pipenv, example: py -3.6 pip install pipenv
run pipenv --python [version] to create the virtual environment in the version of the python you desire. example: pipenv --python 3.6
run pipenv shell to activate your virtual environment.
Just call the correct executable
I am reading How To Learn Python The Hard Way, which uses 2. Recently discovered Invent With Python, which uses 3.
Can I download python 3, and use it when I read Invent With Python, then switch back to python 2 when I want to read How To Learn Python The Hard Way. If so, how would I choose which version I use?
Using 'virtualenv' you can have different isolated Python environments on a single machine. Also you can switch any-time between the different python interpreter versions.
What is virtualenv?
A Virtual Environment is an isolated working copy of Python which allows you to work on a specific project without worry of affecting other projects. It enables multiple side-by-side installations of Python, one for each project. It doesn’t actually install separate copies of Python, but it does provide a clever way to keep different project environments isolated.
How to install?
pip install virtualenv
To create virtual environment for python 2.7 :
root:~# which python2.7
/usr/bin/python2.7
root:~# which python3.4
/usr/local/bin/python3.4
You can also use a Python interpreter of your choice:
root:~# virtualenv -p /usr/bin/python2.7 Vpy27
Running virtualenv with interpreter /usr/bin/python2.7
New python executable in /root/Vpy27/bin/python2.7
Also creating executable in /root/Vpy27/bin/python
Installing setuptools, pip, wheel...done.
To begin using the virtual environment, it needs to be activated:
root:~# source Vpy27/bin/activate
The name of the current virtual environment will now appear on the left of the prompt:
(Vpy27) root:~# python -V
Python 2.7.3
Install packages as usual, for example:
(Vpy27) root:~# pip install junos-eznc >> All pip installs done here, will be available only in this environment.
If you are done working in the virtual environment for the moment, you can deactivate it:
(Vpy27) root:~# deactivate
To create virtual environment for python 3.4:
root:~# which python3.4
/usr/local/bin/python3.4
root:~# virtualenv -p /usr/local/bin/python3.4 Vpy34
root:~# source Vpy34/bin/activate
(Vpy34) root:~# python -V
Python 3.4.4
There is also a way to create virtual environment with already available site-packages.
depends on your system/platform...
I'm currently on Ubuntu 10.10 and have both 2.6 and 3.1 installed. The default system python is 2.6, and python3 is installed as an additional package.
corey#studio17:~$ python
Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
corey#studio17:~$ python3
Python 3.1.2 (release31-maint, Sep 17 2010, 20:27:33)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
similarly, on Windows, I have 2.6 and 3.1 installed (in C:\Python26 and C:\Python31)
easy to switch back and forth.
also.. there are some syntactic differences between 2.x and 3.x that you will need to be aware of (print is a function, etc).
In windows 10 it is a lot easier then what have been given by users above.
Install both the version in separate folders, and then go to environment variable and add the path for both the versions.
Now any time you want to run particular version, just change its order (path) and move it to top of other version, and then restart the cmd and type python this time, you will see that only that particular version of python will run.
For example in my case, I have two version of python one in anaconda(v3.0.6) and another is python 2.7
anytime I want to run the 2.7 i move its path above the anaconda version, as you can see in the screenshot above, and move it below when i want to run anaconda version.
I'm on Windows 10 with Python 3.5 and 2.7. Using PowerShell, here's how I'm switching between versions.
############################################################
# Switch to Python 2.7
############################################################
# Remove python 3.5 from PATH
$current_path = [Environment]::GetEnvironmentVariable("Path", "User")
$python3_path = "C:\Users\REPLACEUSER\AppData\Local\Programs\Python\Python35-32\Scripts\;C:\Users\REPLACEUSER\AppData\Local\Programs\Python\Python35-32\;"
$new_path = $current_path.replace($python3_path, "")
[Environment]::SetEnvironmentVariable("Path", $new_path, "User")
# Add python 2.7 to PATH
# Run PowerShell as administrator
$current_path = [Environment]::GetEnvironmentVariable("Path", "Machine")
$python2_path = "C:\Python27\;C:\Python27\Scripts;"
$new_path = $python2_path + $current_path
[Environment]::SetEnvironmentVariable("Path", $new_path, "Machine")
# Restart PowerShell to see change
# Confirm change
python --version
############################################################
# Switch to Python 3.5
############################################################
# Remove python 2.7 from PATH
# Run PowerShell as administrator
$current_path = [Environment]::GetEnvironmentVariable("Path", "Machine")
$python2_path = "C:\Python27\;C:\Python27\Scripts;"
$new_path = $current_path.replace($python2_path, "")
[Environment]::SetEnvironmentVariable("Path", $new_path, "Machine")
# Add python 3.5 to PATH
$current_path = [Environment]::GetEnvironmentVariable("Path", "User")
$python3_path = "C:\Users\REPLACEUSER\AppData\Local\Programs\Python\Python35-32\Scripts\;C:\Users\REPLACEUSER\AppData\Local\Programs\Python\Python35-32\;"
$new_path = $python3_path + $current_path
[Environment]::SetEnvironmentVariable("Path", $new_path, "User")
# Restart PowerShell to see change
# Confirm change
python --version
Note that you will need to update paths to reflect your Python versions and user profile.
A couple ways on *nix systems:
Install into separate directories (e.g. /usr/local/python2 and /usr/local/python3) and create a link (e.g. /usr/bin/python) which you change to point to whichever executable you want to use.
Same install as above, but set up separate python commands (e.g. /usr/bin/python2 and /usr/bin/python3) and call those when you want to invoke python. Or have the python command default to one of those and a pythonN for the other (N = 2 or 3, whichever isn't the default).
Yes you can. On my machine at least(Vista), v2 and v3 have completely separate idles allowing me to run whichever version I feel like when I feel like it. So go ahead and download v3.
if you are using windows 10 and have python 2.x and 3.x.
open control panel > system and security > system
click advanced system settings.
click environment variables.
click path and edit and then make the path of python version you want to use above that you don't want to use [by click the moveu Up button]
restart powershell.
python --version
Here are my 2 cents.
If you are on a unix based system (Ubuntu, etc..), and you currently have python 2.x. Go ahead and download the python 3.x from Python.org
After installation it will create a separate directory python3
You are done.
To run your programs with python2.x use python filename.py
To run your programs with python3.x, use python3 filename.py
Similarly, to fire up the python2.x and python 3.x interpreter use python and python3 respectively.
I see some of the answers pointing you to virtualenv, I don't think that is what you were asking for, virtualenv is used for isolating Python environments.
If you are using anaconda:
Create a Python 2 environment named py2, install Python 2.7:
conda create --name py2 python=2.7
Activate and use the Python 2 environment:
WINDOWS:
activate py2
LINUX, macOS:
source activate py2
Deactivate the Python 2 environment:
WINDOWS:
deactivate
macOS, LINUX:
source deactivate
Similarly for py3
Create a Python 3 environment named py3, install Python 3.5:
conda create --name py3 python=3.5
and so on..
On Windows, the Python launcher can do this for you.
The PEP article says:
Shebang line parsing
If the first command-line argument does not start with a dash ('-')
character, an attempt will be made to open that argument as a file
and parsed for a shebang line according to the rules in [1]::
#! interpreter [optional-arg]
So simply add a shebang at the beginning of your Python script, like this:
#! python3
#coding=utf-8
import sys
print(sys.version)
...
Or you can pass a command-line parameter to the py.exe launcher:
C:\Users\Administrator>py -3 my_script.py
C:\Users\Administrator>py -2 my_script.py
I've tried 6 solutions so far, like:
virtualenv --python=python py27env
mkvirtualenv --python=python3 py3env etc..
also using virtualenvwrapper package
etc.
None of them worked.
I have Python 3.6 and Python2.7 on my Windows 10 machine, so I renamed C:\Python27\python.exe to python2.exe and
C:\Python36\python.exe to python3.exe or you can even use python36.exe format.
Of course C:\Python27, C:\Python27\Scripts, C:\Python36, C:\Python36\Scripts added to Environment Variables PATH.
(1) For python3 just type:
python3 -m virtualenv venv3
(2) Go to venv folder, activate it with:
Scripts\activate.bat
(3) (venv3) shows it's activated:
(venv3) HOME1#PC C:\Builts\venv3
(4) and then check if it is really 3.6:
python --version
Python 3.6.0
For python2:
python2 -m virtualenv venv2
Result:
(venv2) HOME1#PC C:\Builts\venv2
python --version
Python 2.7.9
I hope it will help.
I just think that there is no need to set up the environment to switch from python2 to python3. Instead when compiling the python script file in the command line, instead of typing python you type python3 then python3 will be used.
# python3 myscript.py
To be possible install virtualenv for python2 without admin access. Rename python.exe to python27.exe at python2 folder;
Include python27 and python27\Scripts at Path environment variable for your account.
call prompt cmd
python27 <path to Scripts\pip.exe of python2.7> install virtualenv