Run in Conda environment without pip-installed packages

Viewed 119

I'm creating a Conda environment and want to make sure it allows anyone to run the scripts in my repository without having to install anything separately. But, I have pip installed some packages on my machine, so, if I understand correctly, some of my imports might work because I pip-installed them and not because they're installed in the Conda environment.

For example, suppose I created an environment with conda create --name my_env python=3.8.8. This shouldn't install Pandas, but if I run import pandas as pd, it works. I believe this is because I've pip-installed Pandas. My question is:

How can I test whether a script works with only packages installed in the conda environment?

2 Answers

You can create a yaml file just from the history of your conda installations:

conda env export --from-history --name my_env > myenv.yml

From that you create a new conda environment, which you can use to test your script with:

conda env create --name conda_only --file myenv.yml

Python has flags to ignore PYTHONPATH (-E) and default system- or user-level site-packages (-S), as well as a combined flag (-I) that does both (see python -h). Try using such flags to isolate from the system. Something like,

conda run -n my_env python -I script.py

Also, it should be clarified that pip install is only an issue like this if you are using the --user flag, which triggers a user-level installation of packages, or some alternate location (e.g., --root or --prefix flags) and have PYTHONPATH set to make those accessible.

Related