I created a python file and used some packages. I installed packages on a virtual Environment. Now, when I try to run that file, it run on the default installed interpreter and I have to activate the virtual Environment every time I have to run that file. Is there any way possible to do that. In conclusion: The code from which the file can select the place where to look for the packages.
3 Answers
You can add the path to the virtual environment's interpreter directly to the shebang at the top of the script. For example, if your virtual environment is stored at /home/ishant/venv, the shebang would be
#!/home/ishant/venv/bin/python
Then, if you execute your script directly (after making it executable with chmod +x or the like), your virtual environment will be used.
(Activating a virtual environment simply updates your PATH variable so that python resolves to the virtual environment, rather than your "regular" environment. You can always access the tools in the virtual enivironment directly instead.)
4 Comments
Command line only (Linux)
Put this in your ~/.bashrc and create the virtual env with name 'venv' inside the project root:
function cd() {
if [[ -d ./venv ]] ; then
deactivate
fi
builtin cd $1
if [[ -d ./venv ]] ; then
. ./venv/bin/activate
fi
}
When cd-ing into a directory, it searches for a virtualenv named venv and disables when leaving.
Alternative with absolute paths (Linux and Windows)
In cases where you want to run the script without a bash, you could run it with the absolute path to the python interpreter inside the virtualenv.
This is from inside the project dir:
# Posix:
/path/to/virtualenvname/bin/python run.py
# Windows:
C:\path\to\virtualenvname\Scripts\python.exe run.py
Or if you want to execute it from outside of the project dir:
# Posix:
/path/to/virtualenvname/bin/python /path/to/projectdir/run.py
# Windows:
C:\path\to\virtualenvname\Scripts\python.exe C:\path\to\projectdir\run.py
2 Comments
venv's if the two aren't the same). It won't work when invoking the script via the PATH or any non-trivial absolute/relative path.Okk So i got your point what i think is why not to add some function in your code so that whenever you excute it it will automatically use vitual environment
--code for linux
import os
os.system("source <virtualenv_name>/bin/activate")
--code for windows
import os
os.system("<virtualenv_name>/bin/activate")
And at last line add
os.system("deactivate")
Add these lines to beginning of your programm see if it works.
May this help you solving your probelem
Thanks!!
5 Comments
source and the activate script set the environments in the current shell – which is gone once os.system completes.'venv' is not recognized as an internal or external command and this is what i added to it: ``` import os os.system("venv/Scripts/activate") ```