How to set environmental variables for Python
Cameron Simpson
cs at cskk.id.au
Mon Jan 17 16:37:56 EST 2022
On 17Jan2022 11:36, Shaozhong SHI <shishaozhong at gmail.com> wrote:
>Set Operation System but not disturbing existing setting. Only to add at
>the command line.
If you mean: "set on the command line so that I run some script using
Python 3.6.1", usually you would just invoke the specific Python 3.6.1
executable.
You can do that directly, or modify $PATH (UNIX, %path% on Windows?) to
find that executable first when looking for the "python" (or "python3"
or "py") command, or use a virtual environment.
The first approach (direct execution) might look like this:
[~]fleet2*> /usr/local/bin/python3.10
Python 3.10.0 (v3.10.0:b494f5935c, Oct 4 2021, 14:59:20) [Clang
12.0.5 (clang-1205.0.22.11)] on darwin
Type "help", "copyright", "credits" or "license" for more
information.
>>>
That's on my local Mac, "[~]fleet2*>" is my prompt, and there's a Python
3.10 installed as /usr/local/bin/python3.10.
The second approach might look like this:
env PATH=/Library/Frameworks/Python.framework/Versions/3.10/bin:$PATH python
That places the Python 3.10 "bin" directory in my $PATH _ahead_ of all
other paths, so that "python" is found there first, thus running the
desired python version:
[~]fleet2*> env PATH=/Library/Frameworks/Python.framework/Versions/3.10/bin:$PATH python3
Python 3.10.0 (v3.10.0:b494f5935c, Oct 4 2021, 14:59:20) [Clang 12.0.5 (clang-1205.0.22.11)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
That particular long path is an artifact of how Python is installed on
my Mac. Adjust for your platform.
The third approach is to use a virtual environment, a common approach
for python development. A virtual environment is a little install
directory based on a particular python version, where you can install a
custom set of third party modules. You make one like this:
/usr/local/bin/python3.10 -m venv venv
That uses the "venv" module from python 3.10 to create a new virtual
environment in the directory "venv" (in the current directory).
From that point onward you want the virtual env "bin" directory in your
PATH:
export PATH=$PWD/venv/bin:$PATH
and thereon, _in that shell_, "python3" will run the python from the
virtual environment (which uses the python3.10 you used to create the
venv) and "pip3" will install modules into that virtual environment, not
disturbing other setups.
Virtualenvs come with an "activate" script whose purpose it to set up
your current shell to use the environment; they essentially do the
"export" above and also fiddle your prompt to remind you that you're
using a particular environment. You don't need to use that - technically
it is enough to directly invoke the python3 executable from the
environment. Fiddling $PATH lets other things find that "python3" by
default.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Python-list
mailing list