Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a python script within a virtual environment using the python binary path?

I have a python environment (it could be conda, virtualenv, venv or global python) - I have a python script - hello.py - that I want to execute within that environment.

If I get the path to the python binary within the environment, for example, in windows with a conda environment called myenv, /path/to/myenv/Scripts/python.exe, and if I execute the script using that python, as shown below, am I guaranteed that the script is executed in that environment, independent of the type of virtual environment? If not, what can I do to ensure such a guarantee?

/path/to/myenv/Scripts/python.exe path/to/hello.py

like image 261
Anand Avatar asked May 29 '26 05:05

Anand


1 Answers

Yes, you're right! Furthermore you can evaluate the used executable by using the following snippet:

import sys

print(sys.executable)

Then you will see the absolute path, e.g. /opt/miniconda/envs/epm/bin/python.

If you're using a Unix system, you can run:

$ echo "import sys; print(sys.version); print(sys.executable)" | /opt/miniconda/envs/epm/bin/python
2.7.15 |Anaconda, Inc.| (default, Dec 14 2018, 13:10:39)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]
/opt/miniconda/envs/epm/bin/python
like image 89
Darius Avatar answered May 30 '26 18:05

Darius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!