问题:确定Python是否在virtualenv中运行

是否可以确定当前脚本是否在virtualenv环境中运行?

Is it possible to determine if the current script is running inside a virtualenv environment?


回答 0

AFAIK进行检查的最可靠方法(以及在virtualenv和pip内部使用的方法)是检查是否存在sys.real_prefix

import sys

if hasattr(sys, 'real_prefix'):
    #...

在virtualenv内,sys.prefix指向virtualenv目录,并sys.real_prefix指向系统Python的“真实”前缀(通常是/usr/usr/local类似的前缀)。

在virtualenv之外,sys.real_prefix不应该存在。

使用VIRTUAL_ENV环境变量不可靠。它是由virtualenv activateshell脚本设置的,但是可以通过直接从virtualenv bin/(或Scripts)目录运行可执行文件来使用virtualenv而不激活它,在这种情况下$VIRTUAL_ENV将不会设置。

The most reliable way to check for this is to check whether sys.prefix == sys.base_prefix. If they are equal, you are not in a virtual environment; if they are unequal, you are. Inside a virtual environment, sys.prefix points to the virtual environment, and sys.base_prefix is the prefix of the system Python the virtualenv was created from.

The above always works for Python 3 stdlib venv and for recent virtualenv (since version 20). Older versions of virtualenv used sys.real_prefix instead of sys.base_prefix (and sys.real_prefix did not exist outside a virtual environment), and in Python 3.3 and earlier sys.base_prefix did not ever exist. So a fully robust check that handles all of these cases could look like this:

import sys

def get_base_prefix_compat():
    """Get base/real prefix, or sys.prefix if there is none."""
    return getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix

def in_virtualenv():
    return get_base_prefix_compat() != sys.prefix

If you only care about supported Python versions and latest virtualenv, you can replace get_base_prefix_compat() with simply sys.base_prefix.

Using the VIRTUAL_ENV environment variable is not reliable. It is set by the virtualenv activate shell script, but a virtualenv can be used without activation by directly running an executable from the virtualenv’s bin/ (or Scripts) directory, in which case $VIRTUAL_ENV will not be set. Or a non-virtualenv Python binary can be executed directly while a virtualenv is activated in the shell, in which case $VIRTUAL_ENV may be set in a Python process that is not actually running in that virtualenv.


回答 1

尝试使用pip -V(注意大写V)

如果您正在运行虚拟环境。它会显示到环境位置的路径。

Try using pip -V (notice capital V)

If you are running the virtual env. it’ll show the path to the env.’s location.


回答 2

这是对Carl Meyer接受的答案的改进。它与适用于Python 3和2的virtualenv以及适用于Python 3 的venv模块一起使用:

import sys


def is_venv():
    return (hasattr(sys, 'real_prefix') or
            (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))

检查是否sys.real_prefix覆盖了virtualenv,非空sys.base_prefix与是否sys.prefix覆盖了venv。

考虑使用如下功能的脚本:

if is_venv():
    print('inside virtualenv or venv')
else:
    print('outside virtualenv or venv')

和以下调用:

$ python2 test.py 
outside virtualenv or venv

$ python3 test.py 
outside virtualenv or venv

$ python2 -m virtualenv virtualenv2
...
$ . virtualenv2/bin/activate
(virtualenv2) $ python test.py 
inside virtualenv or venv
(virtualenv2) $ deactivate

$ python3 -m virtualenv virtualenv3
...
$ . virtualenv3/bin/activate
(virtualenv3) $ python test.py 
inside virtualenv or venv
(virtualenv3) $ deactivate 

$ python3 -m venv venv3
$ . venv3/bin/activate
(venv3) $ python test.py 
inside virtualenv or venv
(venv3) $ deactivate 

This is an improvement of the accepted answer by Carl Meyer. It works with virtualenv for Python 3 and 2 and also for the venv module in Python 3:

import sys


def is_venv():
    return (hasattr(sys, 'real_prefix') or
            (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))

The check for sys.real_prefix covers virtualenv, the equality of non-empty sys.base_prefix with sys.prefix covers venv.

Consider a script that uses the function like this:

if is_venv():
    print('inside virtualenv or venv')
else:
    print('outside virtualenv or venv')

And the following invocation:

$ python2 test.py 
outside virtualenv or venv

$ python3 test.py 
outside virtualenv or venv

$ python2 -m virtualenv virtualenv2
...
$ . virtualenv2/bin/activate
(virtualenv2) $ python test.py 
inside virtualenv or venv
(virtualenv2) $ deactivate

$ python3 -m virtualenv virtualenv3
...
$ . virtualenv3/bin/activate
(virtualenv3) $ python test.py 
inside virtualenv or venv
(virtualenv3) $ deactivate 

$ python3 -m venv venv3
$ . venv3/bin/activate
(venv3) $ python test.py 
inside virtualenv or venv
(venv3) $ deactivate 

回答 3

检查$VIRTUAL_ENV环境变量。

$VIRTUAL_ENV在活动的虚拟环境中,环境变量包含虚拟环境的目录。

>>> import os
>>> os.environ['VIRTUAL_ENV']
'/some/path/project/venv'

一旦运行deactivate/离开虚拟环境,该$VIRTUAL_ENV变量将被清除/为空。Python将引发一个,KeyError因为未设置环境变量。

>>> import os
>>> os.environ['VIRTUAL_ENV']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 678, in __getitem__
    raise KeyError(key) from None
KeyError: 'VIRTUAL_ENV'

当然,这些相同的环境变量检查也可以在外壳程序中的Python脚本之外进行。

Check the $VIRTUAL_ENV environment variable.

The $VIRTUAL_ENV environment variable contains the virtual environment’s directory when in an active virtual environment.

>>> import os
>>> os.environ['VIRTUAL_ENV']
'/some/path/project/venv'

Once you run deactivate / leave the virtual environment, the $VIRTUAL_ENV variable will be cleared/empty. Python will raise a KeyError because the environment variable was unset.

>>> import os
>>> os.environ['VIRTUAL_ENV']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 678, in __getitem__
    raise KeyError(key) from None
KeyError: 'VIRTUAL_ENV'

These same environment variable checks can of course also be done outside of the Python script, in the shell.


回答 4

根据http://www.python.org/dev/peps/pep-0405/#specification上的virtualenv pep,您可以只使用sys.prefix代替os.environ [‘VIRTUAL_ENV’]。

sys.real_prefix在我的virtualenv中不存在,与sys.base_prefix相同。

According to the virtualenv pep at http://www.python.org/dev/peps/pep-0405/#specification you can just use sys.prefix instead os.environ['VIRTUAL_ENV'].

the sys.real_prefix does not exist in my virtualenv and same with sys.base_prefix.


回答 5

要检查您的Virtualenv内部是否存在:

import os

if os.getenv('VIRTUAL_ENV'):
    print('Using Virtualenv')
else:
    print('Not using Virtualenv')

您还可以获取有关您的环境的更多数据:

import sys
import os

print(f'Python Executable: {sys.executable}')
print(f'Python Version: {sys.version}')
print(f'Virtualenv: {os.getenv("VIRTUAL_ENV")}')

To check whether your inside Virtualenv:

import os

if os.getenv('VIRTUAL_ENV'):
    print('Using Virtualenv')
else:
    print('Not using Virtualenv')

You can also get more data on your environment:

import sys
import os

print(f'Python Executable: {sys.executable}')
print(f'Python Version: {sys.version}')
print(f'Virtualenv: {os.getenv("VIRTUAL_ENV")}')

回答 6

这里有多个好的答案,而有些则不太健壮。这里是概述。

怎么不做

不要依赖Python或site-packages文件夹的位置。

如果将它们设置为非标准位置,则并不意味着您实际上在虚拟环境中。用户可以安装多个Python版本,而这些版本并不总是位于您期望的位置。

避免看:

  • sys.executable
  • sys.prefix
  • pip -V
  • which python

此外,不检查的情况下venv.venv或者envs在任何这些路径。对于位置更独特的环境,这将不起作用。例如, Pipenv使用哈希值作为其环境的名称。

VIRTUAL_ENV 环境变量

两者virtualenvvenv设置环境变量$VIRTUAL_ENV激活一个环境时。参见PEP 405

您可以在shell脚本中读出此变量,或使用此Python代码确定是否已设置。

import os
running_in_virtualenv = "VIRTUAL_ENV" in os.environ

# alternative ways to write this, also supporting the case where
# the variable is set but contains an empty string to indicate
# 'not in a virtual environment':
running_in_virtualenv = bool(os.environ.get("VIRTUAL_ENV"))
running_in_virtualenv = bool(os.getenv("VIRTUAL_ENV"))

问题是,这仅在环境由Shell脚本激活有效activate

您可以在不激活环境的情况下启动环境的脚本,因此,如果这是一个问题,则必须使用其他方法。

sys.base_prefix

virtualenvvenv然后按预期pyvenv指向sys.prefix安装在virtualenv内部的Python。

同时,的原始sys.prefix也可作为获得sys.base_prefix

我们可以使用它来检测我们是否在virtualenv中。

import sys
# note: Python versions before 3.3 don't have sys.base_prefix
# if you're not in virtual environment
running_in_virtualenv = sys.prefix != sys.base_prefix

倒退: sys.real_prefix

现在请注意,virtualenv在未设置版本20之前,而是设置了sys.base_prefixsys.real_prefix

为了安全起见,请按照hroncok的答案中的建议进行检查:

import sys

real_prefix = getattr(sys, "real_prefix", None)
base_prefix = getattr(sys, "base_prefix", sys.prefix)

running_in_virtualenv = (base_prefix or real_prefix) != sys.prefix

水蟒

如果您使用的是Anaconda虚拟环境,请查看 Victoria Stuart的答案

There are multiple good answers here, and some less robust ones. Here’s an overview.

How not to do it

Do not rely on on the location of Python or the site-packages folder.

If these are set to non-standard locations, that does not mean you’re actually in a virtual environment. Users can have more than one Python version installed, and those are not always where you expect them to be.

Avoid looking at:

  • sys.executable
  • sys.prefix
  • pip -V
  • which python

Also, do not check for the presence of venv, .venv or envs in any of these paths. This will break for environments with a more unique location. For example, Pipenv uses hash values as the name for its environments.

VIRTUAL_ENV environment variable

Both virtualenv and venv set the environment variable $VIRTUAL_ENV when activating an environment. See PEP 405.

You can read out this variable in shell scripts, or use this Python code to determine if it’s set.

import os
running_in_virtualenv = "VIRTUAL_ENV" in os.environ

# alternative ways to write this, also supporting the case where
# the variable is set but contains an empty string to indicate
# 'not in a virtual environment':
running_in_virtualenv = bool(os.environ.get("VIRTUAL_ENV"))
running_in_virtualenv = bool(os.getenv("VIRTUAL_ENV"))

The problem is, this only works when the environment is activated by the activate shell script.

You can start the environment’s scripts without activating the environment, so if that is a concern, you have to use a different method.

sys.base_prefix

virtualenv, venv and pyvenv point sys.prefix to the Python installed inside of the virtualenv as you would expect.

At the same time, the original value of sys.prefix is also made available as sys.base_prefix.

We can use that to detect if we’re in a virtualenv.

import sys
# note: Python versions before 3.3 don't have sys.base_prefix
# if you're not in virtual environment
running_in_virtualenv = sys.prefix != sys.base_prefix

Fallback: sys.real_prefix

Now watch out, virtualenv before version 20 did not set sys.base_prefix but it set sys.real_prefix instead.

So to be safe, check both as suggested in hroncok’s answer:

import sys

real_prefix = getattr(sys, "real_prefix", None)
base_prefix = getattr(sys, "base_prefix", sys.prefix)

running_in_virtualenv = (base_prefix or real_prefix) != sys.prefix

Anaconda

If you’re using Anaconda virtual environments, check Victoria Stuart’s answer.


回答 7

您可以which python查看虚拟环境中是否指向该环境。

You can do which python and see if its pointing to the one in virtual env.


回答 8

  • 更新于2019年11月(附加)。

我通常使用几个Anaconda安装的虚拟环境(venv)。此代码片段/示例使您可以确定是否处于venv(或系统环境)中,并且还需要脚本使用特定的venv。

添加到Python脚本(代码段):

# ----------------------------------------------------------------------------
# Want script to run in Python 3.5 (has required installed OpenCV, imutils, ... packages):
import os

# First, see if we are in a conda venv { py27: Python 2.7 | py35: Python 3.5 | tf: TensorFlow | thee : Theano }
try:
   os.environ["CONDA_DEFAULT_ENV"]
except KeyError:
   print("\tPlease set the py35 { p3 | Python 3.5 } environment!\n")
   exit()

# If we are in a conda venv, require the p3 venv:
if os.environ['CONDA_DEFAULT_ENV'] != "py35":
    print("\tPlease set the py35 { p3 | Python 3.5 } environment!\n")
    exit()

# See also:
# Python: Determine if running inside virtualenv
# http://stackoverflow.com/questions/1871549/python-determine-if-running-inside-virtualenv  
# [ ... SNIP! ... ]

例:

$ p2
  [Anaconda Python 2.7 venv (source activate py27)]

(py27) $ python  webcam_.py
    Please set the py35 { p3 | Python 3.5 } environment!

(py27) $ p3
  [Anaconda Python 3.5 venv (source activate py35)]

(py35) $ python  webcam.py -n50

    current env: py35
    processing (live): found 2 faces and 4 eyes in this frame
    threaded OpenCV implementation
    num_frames: 50
    webcam -- approx. FPS: 18.59
    Found 2 faces and 4 eyes!
(py35) $

更新1-在bash脚本中使用:

您也可以在bash脚本中使用这种方法(例如,必须在特定虚拟环境中运行的脚本)。示例(添加到bash脚本中):

if [ $CONDA_DEFAULT_ENV ]        ## << note the spaces (important in BASH)!
    then
        printf 'venv: operating in tf-env, proceed ...'
    else
        printf 'Note: must run this script in tf-env venv'
        exit
fi

更新2 [2019年11月]

自从我的原始文章以来,我已经从Anaconda venv转移了(Python本身已经发展了viz -a- viz 虚拟环境)。

重新检查此问题,以下是一些更新的Python代码,您可以将其插入以测试您是否在特定的Python虚拟环境(venv)中运行。

import os, re
try:
    if re.search('py37', os.environ['VIRTUAL_ENV']):
        pass
except KeyError:
    print("\n\tPlease set the Python3 venv [alias: p3]!\n")
    exit()

这是一些说明性代码。

[victoria@victoria ~]$ date; python --version
  Thu 14 Nov 2019 11:27:02 AM PST
  Python 3.8.0

[victoria@victoria ~]$ python
  Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
  [GCC 9.2.0] on linux
  Type "help", "copyright", "credits" or "license" for more information.

>>> import os, re

>>> re.search('py37', os.environ['VIRTUAL_ENV'])
<re.Match object; span=(20, 24), match='py37'>

>>> try:
...     if re.search('py37', os.environ['VIRTUAL_ENV']):
...       print('\n\tOperating in Python3 venv, please proceed!  :-)')
... except KeyError:
...     print("\n\tPlease set the Python3 venv [alias: p3]!\n")
... 

    Please set the Python3 venv [alias: p3]!

>>> [Ctrl-d]
  now exiting EditableBufferInteractiveConsole...

[victoria@victoria ~]$ p3
  [Python 3.7 venv (source activate py37)]

(py37) [victoria@victoria ~]$ python --version
  Python 3.8.0

(py37) [victoria@victoria ~]$ env | grep -i virtual
  VIRTUAL_ENV=/home/victoria/venv/py37

(py37) [victoria@victoria ~]$ python
  Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
  [GCC 9.2.0] on linux
  Type "help", "copyright", "credits" or "license" for more information.

>>> import os, re
>>> try:
...     if re.search('py37', os.environ['VIRTUAL_ENV']):
...       print('\n\tOperating in Python3 venv, please proceed!  :-)')
... except KeyError:
...     print("\n\tPlease set the Python3 venv [alias: p3]!\n")
... 

    Operating in Python3 venv, please proceed!  :-)
>>> 
  • Updated Nov 2019 (appended).

I routinely use several Anaconda-installed virtual environments (venv). This code snippet/examples enables you to determine whether or not you are in a venv (or your system environment), and to also require a specific venv for your script.

Add to Python script (code snippet):

# ----------------------------------------------------------------------------
# Want script to run in Python 3.5 (has required installed OpenCV, imutils, ... packages):
import os

# First, see if we are in a conda venv { py27: Python 2.7 | py35: Python 3.5 | tf: TensorFlow | thee : Theano }
try:
   os.environ["CONDA_DEFAULT_ENV"]
except KeyError:
   print("\tPlease set the py35 { p3 | Python 3.5 } environment!\n")
   exit()

# If we are in a conda venv, require the p3 venv:
if os.environ['CONDA_DEFAULT_ENV'] != "py35":
    print("\tPlease set the py35 { p3 | Python 3.5 } environment!\n")
    exit()

# See also:
# Python: Determine if running inside virtualenv
# http://stackoverflow.com/questions/1871549/python-determine-if-running-inside-virtualenv  
# [ ... SNIP! ... ]

Example:

$ p2
  [Anaconda Python 2.7 venv (source activate py27)]

(py27) $ python  webcam_.py
    Please set the py35 { p3 | Python 3.5 } environment!

(py27) $ p3
  [Anaconda Python 3.5 venv (source activate py35)]

(py35) $ python  webcam.py -n50

    current env: py35
    processing (live): found 2 faces and 4 eyes in this frame
    threaded OpenCV implementation
    num_frames: 50
    webcam -- approx. FPS: 18.59
    Found 2 faces and 4 eyes!
(py35) $

Update 1 — use in bash scripts:

You can also use this approach in bash scripts (e.g., those that must run in a specific virtual environment). Example (added to bash script):

if [ $CONDA_DEFAULT_ENV ]        ## << note the spaces (important in BASH)!
    then
        printf 'venv: operating in tf-env, proceed ...'
    else
        printf 'Note: must run this script in tf-env venv'
        exit
fi

Update 2 [Nov 2019]

Since my original post I’ve moved on from Anaconda venv (and Python itself has evolved viz-a-viz virtual environments).

Reexamining this issue, here is some updated Python code that you can insert to test that you are operating in a specific Python virtual environment (venv).

import os, re
try:
    if re.search('py37', os.environ['VIRTUAL_ENV']):
        pass
except KeyError:
    print("\n\tPlease set the Python3 venv [alias: p3]!\n")
    exit()

Here is some explanatory code.

[victoria@victoria ~]$ date; python --version
  Thu 14 Nov 2019 11:27:02 AM PST
  Python 3.8.0

[victoria@victoria ~]$ python
  Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
  [GCC 9.2.0] on linux
  Type "help", "copyright", "credits" or "license" for more information.

>>> import os, re

>>> re.search('py37', os.environ['VIRTUAL_ENV'])
<re.Match object; span=(20, 24), match='py37'>

>>> try:
...     if re.search('py37', os.environ['VIRTUAL_ENV']):
...       print('\n\tOperating in Python3 venv, please proceed!  :-)')
... except KeyError:
...     print("\n\tPlease set the Python3 venv [alias: p3]!\n")
... 

    Please set the Python3 venv [alias: p3]!

>>> [Ctrl-d]
  now exiting EditableBufferInteractiveConsole...

[victoria@victoria ~]$ p3
  [Python 3.7 venv (source activate py37)]

(py37) [victoria@victoria ~]$ python --version
  Python 3.8.0

(py37) [victoria@victoria ~]$ env | grep -i virtual
  VIRTUAL_ENV=/home/victoria/venv/py37

(py37) [victoria@victoria ~]$ python
  Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
  [GCC 9.2.0] on linux
  Type "help", "copyright", "credits" or "license" for more information.

>>> import os, re
>>> try:
...     if re.search('py37', os.environ['VIRTUAL_ENV']):
...       print('\n\tOperating in Python3 venv, please proceed!  :-)')
... except KeyError:
...     print("\n\tPlease set the Python3 venv [alias: p3]!\n")
... 

    Operating in Python3 venv, please proceed!  :-)
>>> 

回答 9

最简单的方法是运行:which python,如果您位于virtualenv中,它将指向其python而不是全局的python

Easiest way is to just run: which python, if you are in a virtualenv it will point to its python instead of the global one


回答 10

(编辑)我发现那条路,您怎么看?(它还会返回venv基本路径,甚至可以在不检查env变量的readthedocs中使用):

import os
import sys
from distutils.sysconfig import get_config_vars


def get_venv_basedir():
    """Returns the base directory of the virtualenv, useful to read configuration and plugins"""

    exec_prefix = get_config_vars()['exec_prefix']

    if hasattr(sys, 'real_prefix') is False or exec_prefix.startswith(sys.real_prefix):
        raise EnvironmentError('You must be in a virtual environment')

    return os.path.abspath(get_config_vars()['exec_prefix'] + '/../')

(edited) I found that way, what do you think of it ? (it also returns the venv base path and works even for readthedocs where checking the env variable does not):

import os
import sys
from distutils.sysconfig import get_config_vars


def get_venv_basedir():
    """Returns the base directory of the virtualenv, useful to read configuration and plugins"""

    exec_prefix = get_config_vars()['exec_prefix']

    if hasattr(sys, 'real_prefix') is False or exec_prefix.startswith(sys.real_prefix):
        raise EnvironmentError('You must be in a virtual environment')

    return os.path.abspath(get_config_vars()['exec_prefix'] + '/../')

回答 11

已经在这里发布了很多很棒的方法,但是只添加了一个:

import site
site.getsitepackages()

告诉您pip软件包的安装位置。

There are a lot of great methods posted here already, but just adding one more:

import site
site.getsitepackages()

tells you where pip installed the packages.


回答 12

它不是防弹的,但对于UNIX环境,简单的测试如

if run("which python3").find("venv") == -1:
    # something when not executed from venv

对我来说很棒。然后,它比测试某些属性的存在更简单,无论如何,您应该命名venv目录venv

It’s not bullet-proof but for UNIX environments simple test like

if run("which python3").find("venv") == -1:
    # something when not executed from venv

works great for me. It’s simpler then testing existing of some attribute and, anyway, you should name your venv directory venv.


回答 13

在Windows操作系统中,您会看到以下内容:

C:\Users\yourusername\virtualEnvName\Scripts>activate
(virtualEnvName) C:\Users\yourusername\virtualEnvName\Scripts>

括号表示您实际上位于称为“ virtualEnvName”的虚拟环境中。

In windows OS you see something like this:

C:\Users\yourusername\virtualEnvName\Scripts>activate
(virtualEnvName) C:\Users\yourusername\virtualEnvName\Scripts>

Parentheses mean that you are actually in the virtual environment called “virtualEnvName”.


回答 14

一个可能的解决方案是:

os.access(sys.executable, os.W_OK)

就我而言,我真的只是想检测是否可以按原样安装pip物品。尽管这可能不是适用于所有情况的正确解决方案,但请考虑简单地检查一下是否对Python可执行文件的位置具有写权限。

注意:这适用于所有版本的Python,但True如果您使用来运行系统Python,也将返回sudo。这是一个潜在的用例:

import os, sys
can_install_pip_packages = os.access(sys.executable, os.W_OK)

if can_install_pip_packages:
    import pip
    pip.main(['install', 'mypackage'])

A potential solution is:

os.access(sys.executable, os.W_OK)

In my case I really just wanted to detect if I could install items with pip as is. While it might not be the right solution for all cases, consider simply checking if you have write permissions for the location of the Python executable.

Note: this works in all versions of Python, but also returns True if you run the system Python with sudo. Here’s a potential use case:

import os, sys
can_install_pip_packages = os.access(sys.executable, os.W_OK)

if can_install_pip_packages:
    import pip
    pip.main(['install', 'mypackage'])

回答 15

这是一个古老的问题,但是上面的例子太多了。

保持简单:(在Windows 10的Jupyter Notebook或Python 3.7.1终端中)


import sys
print(sys.executable)```

# example output: >> `C:\Anaconda3\envs\quantecon\python.exe`

OR 
```sys.base_prefix```

# Example output: >> 'C:\\Anaconda3\\envs\\quantecon'

This is an old question, but too many examples above are over-complicated.

Keep It Simple: (in Jupyter Notebook or Python 3.7.1 terminal on Windows 10)


import sys
print(sys.executable)```

# example output: >> `C:\Anaconda3\envs\quantecon\python.exe`

OR 
```sys.base_prefix```

# Example output: >> 'C:\\Anaconda3\\envs\\quantecon'

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。