How can I execute Python scripts using Anaconda's version of Python? - python

I recently downloaded the Anaconda distribution for Python. I noticed that if I write and execute a Python script (by double-clicking on its icon), my computer (running on Windows 8) will execute it using my old version of Python rather than Anaconda's version. So for example, if my script contains import matplotlib, I will receive an error. Is there a way to get my scripts to use Anaconda's version of Python instead?
I know that I can just open Anaconda's version of Python in the command prompt and manually import it, but I'd like to set things us so that I can just double-click on a .py file and Anaconda's version of Python is automatically used.

I know this is old, but none of the answers here is a real solution if you want to be able to double-click Python files and have the correct interpreter used without modifying your PYTHONPATH or PATH every time you want to use a different interpreter. Sure, from the command line, activate my-environment works, but OP specifically asked about double-clicking.
In this case, the correct thing to do is use the Python launcher for Windows. Then, all you have to do is add #! path\to\interpreter\python.exe to the top of your script. Unfortunately, although the launcher comes standard with Python 3.3+, it is not included with Anaconda (see Python & Windows: Where is the python launcher?), and the simplest thing to do is to install it separately from here.

Set your python path to the Anaconda version instead
Windows has a built-in dialog for changing environment variables (following guide applies to XP classical view): Right-click the icon for your machine (usually located on your Desktop and called “My Computer”) and choose Properties there. Then, open the Advanced tab and click the Environment Variables button.
In short, your path is:
My Computer ‣ Properties ‣ Advanced ‣ Environment Variables
In this dialog, you can add or modify User and System variables. To change System variables, you need non-restricted access to your machine (i.e. Administrator rights).
Find your PATH variable and add the location of your Anaconda directory.
Example of someone doing it here: How to add to the PYTHONPATH in Windows, so it finds my modules/packages? Make sure that you sub path out for the Anaconda file though.

The instructions in the official Python documentation worked for me: https://docs.python.org/2/using/windows.html#executing-scripts
Launch a command prompt.
Associate the correct file group with .py scripts:
assoc .py=Python.File
Redirect all Python files to the new executable:
ftype Python.File=C:\Path\to\pythonw.exe "%1" %*
The example shows how to associate the .py extension with the .pyw executable, but it works if you want to associate the .py extension with the Anaconda Python executable. You need administrative rights. The name "Python.File" could be anything, you just have to make sure is the same name in the ftype command. When you finish and before you try double-clicking the .py file, you must change the "Open with" in the file properties. The file type will be now ".py" and it is opened with the Anaconda python.exe.

I like to run a "bare-bones" version of Python 2 to verify scripts that I create for other people without an advanced python setup. But Anaconda and Python 3 have a lot of nice features. To enjoy both things on the same computer I do this on my Windows computer which allows me to easily switch.
C:\Users>python --version
Python 2.7.11
C:\Users>conda create --name p3 python=3
C:\Users>conda info --envs
Using Anaconda Cloud api site https://api.anaconda.org
# conda environments:
#
p3 C:\Anaconda3\envs\p3
root * C:\Anaconda3
C:\Users>activate p3
Deactivating environment "C:\Anaconda3"...
Activating environment "C:\Anaconda3\envs\p3"...
[p3] C:\Users>python --version
Python 3.5.1 :: Continuum Analytics, Inc.
For more info: http://conda.pydata.org/docs/test-drive.html

I know this is an old post, but I recently came across with the same problem. However, adding Anaconda to PYTHONPATH wasn't working for me. What got it fixed was the following:
Added Anaconda to the PYTHONPATH and remove any other distribution of Python from any paths.
Opened the command prompt and started python (Here I had to verify that it was indeed running under the Anaconda dist)
Ran the following lines inside anaconda
>>> import sys
>>> sys.path
['','C:\\Anaconda','C:\\Anaconda\\Scripts','C:\\Anaconda\\python27.zip','C:\\Anaconda\\DLLs','C:\\Anaconda\\lib','C:\\Anaconda\\lib\\plat-win','C:\\Anaconda\\lib\\lib-tk','C:\\Anaconda\\lib\\site-packages','C:\\Anaconda\\lib\\site-packages\\PIL','C:\\Anaconda\\lib\\site-packages\\Sphinx-1.2.3-py2.7.egg','C:\\Anaconda\\lib\\site-packages\\win32', 'C:\\Anaconda\\lib\\site-packages\\win32\\lib', 'C:\\Anaconda\\lib\\site-packages\\Pythonwin','C:\\Anaconda\\lib\\site-packages\\runipy-0.1.1-py2.7.egg','C:\\Anaconda\\lib\\site-packages\\setuptools-5.8-py2.7.egg']
Copied the displayed path
Within the script that I'm trying to execute on double click, changed the path to the previously copied one.
import sys
sys.path =['','C:\\Anaconda','C:\\Anaconda\\Scripts','C:\\Anaconda\\python27.zip','C:\\Anaconda\\DLLs','C:\\Anaconda\\lib','C:\\Anaconda\\lib\\plat-win','C:\\Anaconda\\lib\\lib-tk','C:\\Anaconda\\lib\\site-packages','C:\\Anaconda\\lib\\site-packages\\PIL','C:\\Anaconda\\lib\\site-packages\\Sphinx-1.2.3-py2.7.egg','C:\\Anaconda\\lib\\site-packages\\win32', 'C:\\Anaconda\\lib\\site-packages\\win32\\lib', 'C:\\Anaconda\\lib\\site-packages\\Pythonwin','C:\\Anaconda\\lib\\site-packages\\runipy-0.1.1-py2.7.egg','C:\\Anaconda\\lib\\site-packages\\setuptools-5.8-py2.7.egg']
Changed the default application for the script to 'python'
After doing this, my scripts are working on double click.

This solution is not perfectly answering the question because it modifies your .py file into a .bat file but it serves the save purpose, so I think it can help few people out there.
To launch a python script with anaconda's environment : change your .py extension into a .bat extension and add this command line in the beginning of your script :
#echo off & call conda activate <env name> & python -x "%~f0" %* & goto :eof
It will launch a .bat file that will activate your conda environment and execute your python script. This allows you to have a single file that you can copy/paste anywhere and just double click on it to launch it.
Here is an example of the content of the ".bat" file :
#echo off & call conda activate my_environment & python -x "%~f0" %* & goto :eof
print("Hello World!")
input()
import pandas as pd
print('succes')
input()
Hope this helps some people ! Cheers
Note:
If anaconda is not in yourr PATH environment variable, just replace :
conda activate with the path of anaconda activate .bat file, it should look like this C:\ProgramData\Anaconda3\Scripts\activate.bat.
You can also replace the environment name with it's directory, it often looks like that :
C:\Users\<user name>\.conda\envs\<environment name>
Many thanks to this post that helped me figure out this solution:
Python command line -x option

don't know windows 8 but you can probably set the default prog for a specific extension, for example on windows 7 you do right click => open with, then you select the prog you want and select 'use this prog as default', or you can remove your old version of python from your path and add the one of the anaconda

You can try to change the default .py program via policy management. Go to windows, search for regedit, right click it. And then run as administrator. Then, you can search the key word "python.exe" And change your Python27 path to you Anaconda path.

I know that this is an old question, but still there is no accepted answer.
Here is what I'm doing to start a python script with a double click in a specific anaconda environment.
I have found a very useful script in the anaconda3 folder cwp.py. This doesn't activate an environment, but it adds the environment prefix to the path.
You should use it as follow:
python cwp.py PREFIX ARGS
So actually, assuming that your anaconda installation is in C:\Users\User\anaconda3 and your environment is in C:\Users\User\anaconda3\env\myenv then what you have to do is to write the following line in a windows shortcut as a target:
C:\Users\User\anaconda3\pythonw.exe C:\Users\User\anaconda3\cwp.py C:\Users\User\anaconda3\env\myenv C:\Users\User\anaconda3\env\myenv\pythonw.exe path_to_your_script\your-script.py
A double click on the shortcut will start your script!

Related

How to identify python in windows 10

Recently I have install python 3.9.9 in my windows 10.it want show the path
I have typed cmd promt "Wchich Python" it want show
Just type python or python3 in cmd
You can use in your cmd
where python
It will show you the path of all installed python in your device
Just a simple command,
where Python
In Command Prompt, either which python or where python will print the path to your python executable.
If which python or where python does not show the path to your Python executable it is likely that it is not in your PATH variable.
To add your executable to the PATH variable you, search for Environment Variables in the Settings application. This will open the Advanced tab in System Properties. Click the Environment Variables button towards the bottom. You can then edit the PATH variable to include the path to your Python executable. Once you have applied the changes and restarted Command Prompt you can then run which python or where python to confirm your changes have taken effect.

The Python executable is not recognized on Windows 10

I recently installed Python 3.6.3 on my device. When I type python in my cmd window, it gives me this error. I do have the PATH in the environment variables. Path Lists. This should normally fix it, but python is still not recognized.
I had the same problem, due to a stupid decision from Microsoft.
I had another line in my system path variable:
C:\Users\MyUserName\AppData\Local\Microsoft\WindowsApps
And Windows 10 put a python.exe file there that only redirected me to the Python page of the Microsoft Store:
Since this line was above my true Python path, typing python in the cmd prompt opened the Microsoft Store...
Solution:
Type App execution aliases in the Windows 10 search bar, and then uncheck the aliases for python.exe and python3.exe. More information is here.
The path to the Python executable needs to be in the System PATH variable. Note this is not the User PATH variable.
The OP had Python 3.6.3 installed in C:\Python\Python36-32, however a common default location for installation is in the users AppData\Local\Programs\ folder. This post will assume a Python 3.10 installation in this location. Please adjust as needed for your current Python version and path.
You can confirm the path from the command prompt by checking the Python executable directly from the folder.
cd %LOCALAPPDATA%\Programs\Python\Python310
python --version
This should print the Python interpreter version. For example, Python 3.10.4.
Add the following entries to the System PATH:
%LOCALAPPDATA%\Programs\Python\Python310 for the python executable
%LOCALAPPDATA%\Programs\Python\Python310\Scripts for tools such as pip
After adding the path to the System PATH variable, make sure you close and reopen any command prompts, so they use the updated PATH.
If it is still not working, as mentioned in the previous answers, then simply move up the path, as shown in the screenshot.
You get this error, because the python.exe path has not been added to the System environment variable. To do that, simply:
go to the path C:\Users\%Username%\AppData\Local\Programs\Python\Python37-32 which contains python.exe
copy the path and open System environment variables and in the variable section look for variable called Path. If not, create a new variable with Variable Name as Path and value as the copied path
Once you do that, close the window and simply open cmd. Type python and you should get something like this:
If you are trying to install the new Python version, python-3.9.6, then click the checkbox of Add Python 3.9 to PATH
This happens because the path doesn't exist in environment variables.
To fix this:
Rerun the installer
Choose Modify
In optional feature click "Next"
In advanced option tick the "Add Python to environment variables"
Install
All the answers on Stack Overflow_ about it were obsolete, so I decided to add this. The path variable that needs to be added is,
C:\Users\Username\AppData\Local\Programs\Python\Python36-32
Note that everyone may have a different Username.
If you are working with the command prompt and if you are facing the issue even after adding the Python path to system variable PATH:
Remember to restart the command prompt (cmde.exe).
I too was struggling with this issue, and everything was configured correctly. I installed and setup my system path variables as one would. And everything was fine. Then upon reboot windows would not recognize 'python' as a command as if it were unaware of the path variable. Double checked to confirm everything was still setup correctly (it was).
It only started to work again after I manually browsed to the directory in which python.exe existed, and ran 'python'. After that windows seemed to recognize my path variable and I could call 'python' from where ever need be. Very odd. Figured I'd share in case someone else runs into this.
For Python 3.6, there are actually two path entries. Also, it's best to use the %USERPROFILE% rather than hard coding it.
%USERPROFILE%\AppData\Local\Programs\Python\Python36
%USERPROFILE%\AppData\Local\Programs\Python\Python36\Scripts

Activating Anaconda Environment in VsCode

I have Anaconda working on my system and VsCode working, but how do I get VsCode to activate a specific environment when running my python script?
Simply use
shift + cmd + P
Search Select Interpreter
Select it and it will show you the list of your virtual environment created via conda and other python versions
select the environment and you are ready to go.
Quoting the 'Select and activate an environment' docs
Selecting an interpreter from the list adds an entry for python.pythonPath with
the path to the interpreter inside your Workspace Settings.
If Anaconda is your default Python install then it just works if you install the Microsoft Python extension.
The following should work regardless of Python editor or if you need to point to a specific install:
In settings.json edit python.path with something like
"python.pythonPath": "C:\\Anaconda3\\envs\\py34\\python.exe"
Instructions to edit settings.json
Setting python.pythonPath in VSCode's settings.json file doesn't work for me, but another method does. According to the Anaconda documentation at Microsoft Visual Studio Code (VS Code):
When you launch VS Code from Navigator, VS Code is configured to use the Python interpreter in the currently selected environment.
The best option I found is to set the python.venvPath parameter in vscode settings to your anaconda envs folder.
"python.venvPath": "/Users/[...]/Anaconda3/envs"
Then if you bring up the command palette (ctl + shift + P on windows/linux, cmd + shift + P on mac) and type Python: Select Workspace Interpreter all your envs will show up and you can select which env to use.
The python extension will also need to be installed for the Select Workspace Interpreter option.
Note: The Select Workspace Interpreter takes around 10 seconds to come up on my computer using the current version of VSCode.
Although approved answer is correct, I want to show a bit different approach (based on this answer).
Vscode can automatically choose correct anaconda environment if you start vscode from it. Just add to user/workspace settings:
{
"python.pythonPath": "C:/<proper anaconda path>/Anaconda3/envs/${env:CONDA_DEFAULT_ENV}/python"
}
It works on Windows, macOS and probably Unix. Further read on variable substitution in vscode: here.
Unfortunately, this does not work on macOS. Despite the fact that I have export CONDA_DEFAULT_ENV='$HOME/anaconda3/envs/dev' in my .zshrc and "python.pythonPath": "${env.CONDA_DEFAULT_ENV}/bin/python",
in my VSCode prefs, the built-in terminal does not use that environment's Python, even if I have started VSCode from the command line where that variable is set.
Just launch the VS Code from the Anaconda Navigator. It works for me.
Find a note here: https://code.visualstudio.com/docs/python/environments#_conda-environments
As noted earlier, the Python extension automatically detects existing
conda environments provided that the environment contains a Python
interpreter. For example, the following command creates a conda
environment with the Python 3.4 interpreter and several libraries,
which VS Code then shows in the list of available interpreters:
conda create -n env-01 python=3.4 scipy=0.15.0 astroid babel
In contrast, if you fail to specify an interpreter, as with conda create
--name env-00, the environment won't appear in the list.
If you need an independent environment for your project:
Install your environment to your project folder using the --prefix option:
conda create --prefix C:\your\workspace\root\awesomeEnv\ python=3
In VSCode launch.json configuration set your "pythonPath" to:
"pythonPath":"${workspaceRoot}/awesomeEnv/python.exe"
Python Path is now deprecated and now you should set Conda Path instead. This way you can pick different environements on the fly.
Click ctrl + , then search for Conda Path and add absolute path to script, e.g.:
C:\Users\{myUser}\miniconda3\Scripts\conda.exe
Pick specific environment for each project in bottom left corner or through Command Pallete (ctrl + Shift + P -> search Python: Select Interpreter)
The simplest way to do it -
First open up terminal or command line and navigate to the project directory where you created the virtual environment.
Then activate the virtual environment with the command
conda activate venv_name
Once activated, in terminal type -
code .
This will open the vscode with the activated virtual environment. Look at the bottom of the pic. The dot after code . tells terminal to open the current directory in vscode.
I found out that if we do not specify which python version we want the environment which is created is completely empty. Thus, to resolve this issue what I did is that I gave the python version as well. i.e
conda create --name env_name python=3.6
so what it does now is that it installs python 3.6 and now we can select the interpreter. For that follow the below-mentioned steps:
Firstly, open the command palette using Ctrl + Shift + P
Secondly, Select Python: select Interpreter
Now, Select Enter interpreter path
We have to add the path where the env is, the default location will be
C:\Users\YourUserName\Anaconda3\envs\env_name
Finally, you have successfully activated your environment.
It might now be the best way but it worked for me. Let me know if there is any issue.
I found a hacky solution replace your environment variable for the original python file so instead it can just call from the python.exe from your anaconda folder, so when you reference python it will reference anaconda's python.
So your only python path in env var should be like:
"C:\Anaconda3\envs\py34\", or wherever the python executable lives
If you need more details I don't mind explaining. :)
As I was not able to solve my problem by suggested ways, I will share how I fixed it.
First of all, even if I was able to activate an environment, the corresponding environment folder was not present in C:\ProgramData\Anaconda3\envs directory.
So I created a new anaconda environment using Anaconda prompt,
a new folder named same as your given environment name will be created in the envs folder.
Next, I activated that environment in Anaconda prompt.
Installed python with conda install python command.
Then on anaconda navigator, selected the newly created environment in the 'Applications on' menu.
Launched vscode through Anaconda navigator.
Now as suggested by other answers, in vscode, opened command palette with Ctrl + Shift + P keyboard shortcut.
Searched and selected Python: Select Interpreter
If the interpreter with newly created environment isn't listed out there, select Enter Interpreter Path and choose the newly created python.exe which is located similar to C:\ProgramData\Anaconda3\envs\<your-new-env>\ .
So the total path will look like C:\ProgramData\Anaconda3\envs\<your-nev-env>\python.exe
Next time onwards the interpreter will be automatically listed among other interpreters.
Now you might see your selected conda environment at bottom left side in vscode.
"python.pythonPath" is deprecated, quote from vscode:
The "python.pythonPath" setting in your settings.json is no longer
used by the Python extension. If you want, you can use a new setting
called "python.defaultInterpreterPath" instead. Keep in mind that you
need to change the value of this setting manually as the Python
extension doesn’t modify it when you change interpreters. Learn more.
Thus, IF you want to assign the path manually (not reccommended, as explained above), open the "settings.json" of your workspace or the default one and use
{
"python.defaultInterpreterPath": "C:\\Users\\MYUSER\\anaconda3\\envs\\testenv\\python.exe"
}

How to control what version of Python is run when double clicking a file?

Is there a way to control what version of python is run when double clicking on a py file? From the command line and in environments such as eclipse I can control what version is run. But from double clicking I am not sure.
I have 2.6 and 2.7 installed. 2.6 is for some application specific stuff and I want to make 2.7 the default. I have added "C:\Python27" to the PATH environment variable and that works well at the command line. C:\path\to\some\file>python someFile.py will run the file in 2.7. But if I double click the same file from explorer it runs 2.6. How to get it to run 2.7?
On Windows, you have to modify the file associations, for example via Right Click → Open with ... → Choose default program or the Control Panel's Folder Settings. You can choose between multiple python installations by navigating to the python.exe you want via the Browse button:
Alternatively, you can change the association in a command shell by typing
ftype Python.File="C:\Python27\python.exe" "%1" %*
Note that this requires administrator rights. If UAC is enabled on your machine, right click cmd in the start menu and select Run as administrator.
On freedesktop.org-compatible desktops, you can configure the association with xdg-mime.
On debian-based distributions, you can change the default python with update-alternatives. On all systems, you can also symlink the python in your path to the correct implementation, like this:
$ sudo ln -sf python2.7 /usr/bin/python
If the file is marked executable, it can also be executed directly from the command line or GUI if it starts with #! and the name of the interpreter:
#!/usr/bin/env python
To choose a specific Python version just for your program, you can start your Python program with one of the following lines:
#!/usr/bin/env python2.7
#!/usr/bin/python2.7
OK I have found the Python Launcher, which does exactly what I am after. Download can be found here. Installing this gave me the option for "Python Launcher for Windows (GUI)" when changing the file association via the right click menu.
Adding the shebang line
#!/usr/bin/python2.7
forces the script to run in 2.7.
This works great as I can control what version of python is running and users never need to know. No need for bat files, or dragging onto shortcuts etc. Nice and clean, and most importantly, no room for user error.
You can use ASSOC and FTYPE
assoc .py=pyfile
ftype pyfile=c:\Python27\python.exe %1
You will find answer in answers to the following questions:
How to execute python scripts in windows?
Using older Python 2.x while having both Python 2.x and 3.x installed on Windows
Temporary file association for single cmd.exe session
How to write a batch file showing path to executable and version of Python handling Python scripts on Windows?

How can I get python in the command prompt on Windows?

I have just installed Python on my Windows 7. I thought that after that I will be able to run python on the command prompt but it is not the case. After the installation I also found out that I can run the python command shell. This is nice. But what should I do if I want to save my program in a file and then I want to run this program (in Linux, for example, I typed "python file_name.py" in the command line).
You need to add the python bin directory to your path. Follow the instructions here and add c:\python26\bin to the path (unless you installed python in a non-default location).
Is python.exe in your windows path? Try to look at the PATH environment variable and see if the installation folder of python is listed there.
You need to update your environment variables to include the path to the Python executable.
On XP you can do this by right clicking on "My Computer" -> Properties and then going to the "Advanced" tab.

Categories