Repository: pypa/pipenv

Issue:
Using pipenv installed under pipx gives "Pipenv found itself running within a virtual environment"
### Issue description

I have pipenv installed using pipx, which means that it's installed in a venv. This is deliberate, as I do *not* want to install pipenv and all its dependencies in my system Python, and there's no other recommended approach in the pipenv docs for how to install pipenv standalone.

When I run pipenv, I get the error "Pipenv found itself running within a virtual environment". However, I see no evidence that pipenv didn't create a virtual environment, nor do I see any problems resulting from running pipenv in this way.

**Note** There are a number of duplicates for this issue, but they all refer to MacOS and (as far as I can see) the Homebrew version of Python. This report is for Windows using the normal python.org installer. Please do not close this as a duplicate without ensuring that whichever issue is being treated as the "master" is updated to note that it is not a MacOS specific problem.

### Expected result

* Not to get a "Courtesy Notice" that is neither helpful nor, as far as I can see, accurate.
* Not to have to set environment variables to use pipenv normally.

### Actual result

When possible, provide the verbose output (`--verbose`), especially for locking and dependencies resolving issues.

```
PS 17:30 {00:01.134} D:\Work\Scratch\pypidata
>pipenv run python -c "import sys; print(sys.executable)"
Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning.
C:\Users\Gustav\.virtualenvs\pypidata-OL7vfyqD\Scripts\python.exe
```

Note that `sys.executable` is in a pipenv-created directory, so it apparently *did* create one...

### Steps to replicate

See above.

<details><summary>$ pipenv --support</summary>

Pipenv version: `'2020.6.2'`

Pipenv location: `'c:\\users\\gustav\\.local\\pipx\\venvs\\pipenv\\lib\\site-packages\\pipenv'`

Python location: `'c:\\users\\gustav\\.local\\pipx\\venvs\\pipenv\\scripts\\python.exe'`

Python installations found:

  - `3.8.5`: `C:\Users\Gustav\AppData\Local\Programs\Python\Python38\python.exe`

PEP 508 Information:

```
{'implementation_name': 'cpython',
 'implementation_version': '3.8.5',
 'os_name': 'nt',
 'platform_machine': 'AMD64',
 'platform_python_implementation': 'CPython',
 'platform_release': '10',
 'platform_system': 'Windows',
 'platform_version': '10.0.19041',
 'python_full_version': '3.8.5',
 'python_version': '3.8',
 'sys_platform': 'win32'}
```

System environment variables:

  - `ALLUSERSPROFILE`
  - `APPDATA`
  - `COMMONPROGRAMFILES`
  - `COMMONPROGRAMFILES(X86)`
  - `COMMONPROGRAMW6432`
  - `COMPUTERNAME`
  - `COMSPEC`
  - `DRIVERDATA`
  - `GIT_INSTALL_ROOT`
  - `HOMEDRIVE`
  - `HOMEPATH`
  - `LOCALAPPDATA`
  - `LOGONSERVER`
  - `NUMBER_OF_PROCESSORS`
  - `ONEDRIVE`
  - `ONEDRIVECONSUMER`
  - `OS`
  - `PATH`
  - `PATHEXT`
  - `POWERSHELL_DISTRIBUTION_CHANNEL`
  - `PROCESSOR_ARCHITECTURE`
  - `PROCESSOR_IDENTIFIER`
  - `PROCESSOR_LEVEL`
  - `PROCESSOR_REVISION`
  - `PROGRAMDATA`
  - `PROGRAMFILES`
  - `PROGRAMFILES(X86)`
  - `PROGRAMW6432`
  - `PSMODULEPATH`
  - `PUBLIC`
  - `SYSTEMDRIVE`
  - `SYSTEMROOT`
  - `TEMP`
  - `TMP`
  - `USERDOMAIN`
  - `USERDOMAIN_ROAMINGPROFILE`
  - `USERNAME`
  - `USERPROFILE`
  - `VIRTUAL_ENV_DISABLE_PROMPT`
  - `WINDIR`
  - `WORK_DIRECTORY`
  - `WSLENV`
  - `WT_PROFILE_ID`
  - `WT_SESSION`
  - `PIP_DISABLE_PIP_VERSION_CHECK`
  - `PYTHONDONTWRITEBYTECODE`
  - `PIP_SHIMS_BASE_MODULE`
  - `PIP_PYTHON_PATH`
  - `PYTHONFINDER_IGNORE_UNSUPPORTED`

PipenvÔÇôspecific environment variables:


DebugÔÇôspecific environment variables:

  - `PATH`: `C:\Program Files\PowerShell\7;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\PowerShell\7\;C:\Program Files\Docker\Docker\resources\bin;C:\ProgramData\DockerDesktop\version-bin;C:\Users\Gustav\scoop\apps\cyg\current\bin;C:\Users\Gustav\scoop\shims;C:\Users\Gustav\AppData\Local\Microsoft\WindowsApps;C:\Users\Gustav\.local\bin;C:\Users\Gustav\.local\scripts;C:\Users\Gustav\AppData\Local\Microsoft\WindowsApps;C:\Users\Gustav\AppData\Local\Programs\Microsoft VS Code\bin`


---------------------------

Contents of `Pipfile` ('D:\\Work\\Scratch\\pypidata\\Pipfile'):

```toml
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]

[packages]
requests = "*"
mousebender = "*"

[requires]
python_version = "3.8"

```


Contents of `Pipfile.lock` ('D:\\Work\\Scratch\\pypidata\\Pipfile.lock'):

```json
{
    "_meta": {
        "hash": {
            "sha256": "6d4c907ebdbb3297b0bd85f38e0c82f7ae7d5097192f1c8b85ce25de8c7abff2"
        },
        "pipfile-spec": 6,
        "requires": {
            "python_version": "3.8"
        },
        "sources": [
            {
                "name": "pypi",
                "url": "https://pypi.org/simple",
                "verify_ssl": true
            }
        ]
    },
    "default": {
        "attrs": {
            "hashes": [
                "sha256:08a96c641c3a74e44eb59afb61a24f2cb9f4d7188748e76ba4bb5edfa3cb7d1c",
                "sha256:f7b7ce16570fe9965acd6d30101a28f62fb4a7f9e926b3bbc9b61f8b04247e72"
            ],
            "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'",
            "version": "==19.3.0"
        },
        "certifi": {
            "hashes": [
                "sha256:5930595817496dd21bb8dc35dad090f1c2cd0adfaf21204bf6732ca5d8ee34d3",
                "sha256:8fc0819f1f30ba15bdb34cceffb9ef04d99f420f68eb75d901e9560b8749fc41"
            ],
            "version": "==2020.6.20"
        },
        "chardet": {
            "hashes": [
                "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae",
                "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691"
            ],
            "version": "==3.0.4"
        },
        "idna": {
            "hashes": [
                "sha256:b307872f855b18632ce0c21c5e45be78c0ea7ae4c15c828c20788b26921eb3f6",
                "sha256:b97d804b1e9b523befed77c48dacec60e6dcb0b5391d57af6a65a312a90648c0"
            ],
            "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'",
            "version": "==2.10"
        },
        "mousebender": {
            "hashes": [
                "sha256:a6f9adfbd17bfb0e6bb5de9a27083e01dfb86ed9c3861e04143d9fd6db373f7c",
                "sha256:c5953026378e5dcc7090596dfcbf73aa5a9786842357273b1df974ebd79bd760"
            ],
            "index": "pypi",
            "version": "==2.0.0"
        },
        "packaging": {
            "hashes": [
                "sha256:4357f74f47b9c12db93624a82154e9b120fa8293699949152b22065d556079f8",
                "sha256:998416ba6962ae7fbd6596850b80e17859a5753ba17c32284f67bfff33784181"
            ],
            "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'",
            "version": "==20.4"
        },
        "pyparsing": {
            "hashes": [
                "sha256:c203ec8783bf771a155b207279b9bccb8dea02d8f0c9e5f8ead507bc3246ecc1",
                "sha256:ef9d7589ef3c200abe66653d3f1ab1033c3c419ae9b9bdb1240a85b024efc88b"
            ],
            "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2'",
            "version": "==2.4.7"
        },
        "requests": {
            "hashes": [
                "sha256:b3559a131db72c33ee969480840fff4bb6dd111de7dd27c8ee1f820f4f00231b",
                "sha256:fe75cc94a9443b9246fc7049224f75604b113c36acb93f87b80ed42c44cbb898"
            ],
            "index": "pypi",
            "version": "==2.24.0"
        },
        "six": {
            "hashes": [
                "sha256:30639c035cdb23534cd4aa2dd52c3bf48f06e5f4a941509c8bafd8ce11080259",
                "sha256:8b74bedcbbbaca38ff6d7491d76f2b06b3592611af620f8426e82dddb04a5ced"
            ],
            "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2'",
            "version": "==1.15.0"
        },
        "urllib3": {
            "hashes": [
                "sha256:91056c15fa70756691db97756772bb1eb9678fa585d9184f24534b100dc60f4a",
                "sha256:e7983572181f5e1522d9c98453462384ee92a0be7fac5f1413a1e35c56cc0461"
            ],
            "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' and python_version < '4'",
            "version": "==1.25.10"
        }
    },
    "develop": {}
}

```
</details>


Discussion:
Can you please have a try against the master branch to see if the issue is gone? Will cut a new release shortly if so.
No, it still happens in master, I'm afraid.

```
>pipenv --version
pipenv, version 2020.6.2.dev0
>pipenv
Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning.
Usage: pipenv [OPTIONS] COMMAND [ARGS]...
```
Just to clarify here - I *do* have pipenv running in a virtualenv. So the initial part of the "courtesy notice" is correct. What is not correct, as far as I can see, is the statement that it will "automatically use that environment". It doesn't, and furthermore I don't *want* it to. I want to be able to install pipenv in an isolated environment, *not* in my system (or user) site-packages, and have it work.

In practice, the issue here is that the message and the behaviour don't match - and what I want is the current behaviour, but not the (incorrect) message.

I'm not clear why anyone would want pipenv to automatically use an existing virtual environment. And in practice, nothing I've tried has been able to provoke it to do so...
Update: Looking through the source, I see that one difference which may be relevant here is that I run pipenv using my virtualenv Python, but I do *not* activate that virtualenv. So `sys.executable` is in a virtualenv, and `is_in_virtualenv` will therefore be true, but the virtualenv is not on `PATH`, and `VIRTUAL_ENV` is not set (so `Project.virtualenv_location` won't see the environment pipenv is installed in).

Resolving patch:
diff --git a/pipenv/environments.py b/pipenv/environments.py
--- a/pipenv/environments.py
+++ b/pipenv/environments.py
@@ -367,16 +367,16 @@ def is_quiet(threshold=-1):
     return PIPENV_VERBOSITY <= threshold
 
 
-def _is_using_venv():
+def is_using_venv():
     # type: () -> bool
     """Check for venv-based virtual environment which sets sys.base_prefix"""
-    return sys.prefix != getattr(sys, "base_prefix", sys.prefix)
-
-
-def _is_using_virtualenv():
-    # type: () -> bool
-    """Check for virtualenv-based environment which sets sys.real_prefix"""
-    return getattr(sys, "real_prefix", None) is not None
+    if getattr(sys, 'real_prefix', None) is not None:
+        # virtualenv venvs
+        result = True
+    else:
+        # PEP 405 venvs
+        result = sys.prefix != getattr(sys, 'base_prefix', sys.prefix)
+    return result
 
 
 def is_in_virtualenv():
@@ -388,16 +388,9 @@ def is_in_virtualenv():
     """
 
     pipenv_active = os.environ.get("PIPENV_ACTIVE", False)
-    virtual_env = None
-    use_system = False
+    virtual_env = bool(os.environ.get("VIRTUAL_ENV"))
     ignore_virtualenvs = bool(os.environ.get("PIPENV_IGNORE_VIRTUALENVS", False))
-
-    if not pipenv_active and not ignore_virtualenvs:
-        virtual_env = any([
-            _is_using_virtualenv(), _is_using_venv(), os.environ.get("VIRTUAL_ENV")
-        ])
-        use_system = bool(virtual_env)
-    return (use_system or virtual_env) and not (pipenv_active or ignore_virtualenvs)
+    return virtual_env and not (pipenv_active or ignore_virtualenvs)
 
 
 PIPENV_SPINNER_FAIL_TEXT = fix_utf8(u"✘ {0}") if not PIPENV_HIDE_EMOJIS else ("{0}")
diff --git a/pipenv/project.py b/pipenv/project.py
--- a/pipenv/project.py
+++ b/pipenv/project.py
@@ -25,7 +25,7 @@
 from .environments import (
     PIPENV_DEFAULT_PYTHON_VERSION, PIPENV_IGNORE_VIRTUALENVS, PIPENV_MAX_DEPTH,
     PIPENV_PIPFILE, PIPENV_PYTHON, PIPENV_TEST_INDEX, PIPENV_VENV_IN_PROJECT,
-    PIPENV_USE_SYSTEM, is_in_virtualenv, is_type_checking
+    PIPENV_USE_SYSTEM, is_in_virtualenv, is_type_checking, is_using_venv
 )
 from .vendor.requirementslib.models.utils import get_default_pyproject_backend
 from .utils import (
@@ -349,7 +349,7 @@ def pipfile_package_names(self):
 
     def get_environment(self, allow_global=False):
         # type: (bool) -> Environment
-        is_venv = is_in_virtualenv()
+        is_venv = is_in_virtualenv() or is_using_venv()
         if allow_global and not is_venv:
             prefix = sys.prefix
             python = sys.executable


Test patch: