Automatically open a virtual environment when calling a python script in Windows - python

This question has been asked before, but the answers are all several years old and I could not get any to work for me, so I would appreciate some help.
The question is simple, really: I have a python script, and a virtual environment I want it to run in when I double-click it, or call it from another program. How can I achieve this?

you must add packages directory address to your sys.path
sys.path a built-in variable within the sys module. It contains a list of directories that the interpreter will search in for the required module.
add line below to top of your script, now you can double click on script file and every thing must work fine
import sys; sys.path.append("./<environment path>/Lib/site-packages")
this is simple solution however, as sinoroc said it's not good solution because in this situation you are using system interpreter not virtual environment interpreter so i wouldn't be surprised if things don't work as expected.
also you can download all packages that you need and extract them into single folder and add that folder to sys.path
first download packages you need with command below
pip download <package names> --dest <directory name>
for example:
pip download requests --dest packages
at the end add folder contain you packages to your path
import sys; sys.path.append("./<packages directory>")
Recommended Solution
the best solution is that write little batch script for windows or shell script for linux that automatically active virtual environment and then run your script
first create file with .bat extention for windows or .sh extension for linux and then add line below to it
for .bat file
<environment path>\Scripts\activate && python <script name>.py
for .sh file
source <environment path>/bin/activate && python <script name>.py
now you can click on this batch script *.bat file or shell script *.sh file and everything work's fine

Some ideas
Shebang
Place a shebang pointing to the Python interpreter inside the virtual environement with the full path at the top of the script.
#!/path/to/my/venv/bin/python
import sys
print(sys.executable)
Shell/batch script
Write a shell script wrapping the call to the actual Python script:
#!/usr/bin/env sh
/path/to/my/venv/bin/python /path/to/my/script.py
Python wrapper
#!/usr/bin/env python3
import subprocess
command = [
'/path/to/my/venv/bin/python',
'/path/to/my/script.py',
]
subprocesss.check_call(command)

Related

How can I run a python script in anaconda environment with another python script? (not by .bat ro .sh file)

I have a python script which I want to run it in an anaconda environment because it uses some library like NumPy and I'm not going to install them.
I can easily write something like this:
# for Windows:
C:\ProgramData\Anaconda3\Scripts\activate.bat && python script.py arg
# for Linux:
source activate base
python script.py arg
but then I should have two scripts. a batch file and a shell script which is not desirable.
I like to have a single solution and independent of OS.
So I thought maybe it's good to have a python script which activates anaconda environment then run my script.(So I can handle OS there). I could do it by subprocess.call(). However, it gives an additional message which it's not desirable and I couldn't solve it even with a StackOverflow question.
Now I'm asking do you have a solution to run a python script in anaconda environment with another python script? (which of course doesn't give a notification like my solution.)

Python script that can run from OSX Finder and Windows Explorer

I have a bunch of useful Python3 scripts that I use in different OS environments. They run fine when called from the terminal but I want to run them from both Windows Explorer and OSX Finder. In Windows, that is not an issue as the *.py files get associated with the installed interpreter.
For OSX, I am having some problems. I tried using the shebang line.
#!/usr/bin/python3
But Finder doesn't recognize it as a script. How do I make Finder recognize *.py files as scripts? I am interested in maximum portability with as few OS modifications as possible.
Also I explicitly specified the interpreter location above. It will be in different locations for different OSes. Is there a way to make it multi-OS so that if it doesn't find it in one location, it will try another? Say if I want to run it from one of Ubuntu's GUI File Manager.
EDIT: Here's more info on my use case. I want to go to a new computer and git clone my repo of Python3 scripts and be able to run them from within the GUI file manager with minimal changes to the new computer.
To make the script more portable use #!/usr/bin/env python3 as shebang. Side effect will be that it will run the first python3 interpreter it finds in the $PATH (Unix StackExchange question on that subject)
To run the script from the finder try to chmod the file. i.e.
chmod +x FILE
Found another possibility here: Link to the Blog
Make this the first line of your Python script "#!/usr/bin/env python"
Change the extension of the script file to ".command" i.e. my_python_script.command
In Terminal make the Python script file executable by running "chmod +x my_python_script.command"
Now when you double click the Python script in Finder it will open a terminal window and run.
Alternative I found would be this but it needs system modification: Superuser question

Running a python program in Windows?

I have Python 3.6 and Windows 7.
I am able to successfully start the python interpreter in interactive mode, which I have confirmed by going to cmd, and typing in python, so my computer knows how to find the interpreter.
I am confused however, as to how to access files from the interpreter. For example, I have a file called test.py (yes, I made sure the correct file extension was used).
However, I do not know how to access test.py from the interpreter. Let us say for the sake of argument that the test.py file has been stored in C:\ How then would I access test.py from the interpreter?
The simplest way would be to just do the following in cmd:
C:\path\to\file\test.py
Windows recognizes the file extension and runs it with Python.
Or you can change the directory to where the Python program/script is by using the cd command in the command prompt:
cd C:\path\to\file
Start Python in the terminal and import the script using the import function:
import test
You do not have to specify the .py file extension. The script will only run once per process so you'll need to use the reload function to run it after it's first import.
You can make python run the script from a specific directory:
python C:\path\to\file\test.py
In command prompt you need to navigate to the file location. In your case it is in C:\ drive, so type:
cd C:\
and then proceed to run your program:
python test.py
or you could do it in one line:
python C:\test.py
I may be misunderstanding what you are seeking, but I think what you are asking for is a IDE-like environment where you can load Python scripts, edit, and debug.
You already have IDLE, https://docs.python.org/3.6/library/idle.html, which came with the Python installation.
There are many IDEs available for Python. https://wiki.python.org/moin/IntegratedDevelopmentEnvironments Personally, I like using PyDev on Eclipse.

How can I execute Python scripts using Anaconda's version of 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!

Starting Python tutorials but have some beginner questions

Hello I am attempting to learn Python using django in powershell on windows to create a simple CRUD app but have some questions regarding the setup and usage.
I have setup the path environment variable to include paths to a folder that includes test .py scripts that I thought allowed me to run directly from a c:\ in powershell but when I try to run the samples using:
c:\> python test1.py
c:\> python .\test1.py
It does not work and I get:
c:\Python27\python.exe: can't open file '.\test1.py':[Errno 2] No such file or directory
but if I CD to path first and run it works fine and I get the output in the powershell window itself:
c:\> cd c:\Python27\Scripts
c:\Python27\Scripts> python test1.py
In addition if I just type the name of the script from the root c:\ prompt such as:
c:\> c:\Python27\Scripts\test1.py
c:\> test1.py
it runs the script by opening in a dos box that that closes immediately since it ran the script and finished.
What is the difference between these methods and is there an issue running scripts one way or the other?
The issue here is that in the first case:
c:\> python test1.py
c:\> python .\test1.py
You're running python itself, and then the file is an argument to the interpreter. So python will be affected by PATH, but the file is relative. Both of these file paths mean to look for it in the same directory, which is the root of C:. Since the file isn't located there, the error results.
The second case:
c:\> c:\Python27\Scripts\test1.py
c:\> test1.py
It's the file itself being run as an "executable", factoring in PATH. On Unix, this would use the shebang and invoke the shell in pretty much the same way, however that's not the case on Windows. Instead, it's basically running whatever is associated with the .py extension at the OS level, which is likely to invoke a new Python interpreter in a new Window, hence the behavior where it disappears after it's done.
On Windows, since there's no shebang, I generally prefer to run the python interpreter directly and pass the script as an argument. I would generally switch to the directory the script is located in first. This way it's more shell-centric, and, I think, straightforward.
You can run pushd . to save the cwd, and then after popd to go back, optionally. That would work in .cmd files and similar, too.
Are you sure test1.py is in C: and not in c:\Python27\Scripts

Categories