Specifying Anaconda environment upon call

时间:2019-04-17 01:25:33

标签: python command-line anaconda

Anaconda allows users to have different versions of Python and R installed at the same time. These versions are managed in environments, which can be activated and deactivated according to the user's preference.

I would like to specify which version of Python or R to use when I execute a script on the command line (regardless of which environment is active). This could look like

python -version 3.7 myPy3Script.py
python -version 2.7 myPy2Script.py

Here, the first command would execute my script in Python 3, whereas the second line would execute my second script in Python 2.

Can I actually do that in practice? If so, how?

Of course, I could just specify the path to the respective python executable. However, would the libraries be loaded correctly in this case? (See this issue). Also, would there be a way to avoid typing in lengthy paths?

1 个答案:

答案 0 :(得分:1)

Probably the easiest, and Anaconda's intended way, to specify which Python version to use is to activate your environment before each call. So something like:

conda activate <Python 3 env> && python myPy3Script.py
conda activate <Python 2 env> && python myPy2Script.py

Alternatively, if you are using Linux (or other Unix system), you can define a shebang at the beginning of your file to specify the program to execute the script with. So for instance, your myPy3Script.py might look like this:

#!/path/to/python3

<Code within your script>
...