Repository: pypa/pipenv

Issue:
Virtualenv is not being activated on Windows 10
Be sure to check the existing issues (both open and closed!).

Describe the issue briefly here.

When running pipenv in a new folder on Windows 10, the virtualenv and Pipfile are created, but the virtualenv is not used. Running `$ pipenv --venv` shows `No virtualenv has been created for this project yet!`

Any subsequent pipenv commands tries to create another virtualenv. When installing a package like `pipenv install requests`, pipenv tries to install the package globally.

Please run `$ python -m pipenv.help`, and paste the results here.

```
C:\Users\Nelson\temp>python -m pipenv.help

Pipenv version: `'11.5.2'`

Pipenv location: `'C:\\Program Files (x86)\\Python36-32\\lib\\site-packages\\pipenv'`

Python location: `'C:\\Program Files (x86)\\Python36-32\\python.exe'`

Other Python installations in `PATH`:

  - `2.7`: `C:\Python27\python.exe`
  - `3.6`: `C:\Program Files (x86)\Python36-32\python.exe`

  - `3.6.4`: `C:\Program Files (x86)\Python36-32\python.exe`
  - `2.7.12`: `C:\Python27\python.exe`
  - `3.6.4`: `C:\Windows\py.exe`

PEP 508 Information:

{'implementation_name': 'cpython',
 'implementation_version': '3.6.4',
 'os_name': 'nt',
 'platform_machine': 'AMD64',
 'platform_python_implementation': 'CPython',
 'platform_release': '10',
 'platform_system': 'Windows',
 'platform_version': '10.0.17115',
 'python_full_version': '3.6.4',
 'python_version': '3.6',
 'sys_platform': 'win32'}

System environment variables:

  - `ALLUSERSPROFILE`
  - `APPDATA`
  - `COMMONPROGRAMFILES`
  - `COMMONPROGRAMFILES(X86)`
  - `COMMONPROGRAMW6432`
  - `COMPUTERNAME`
  - `COMSPEC`
  - `DRIVERDATA`
  - `FPS_BROWSER_APP_PROFILE_STRING`
  - `FPS_BROWSER_USER_PROFILE_STRING`
  - `HOMEDRIVE`
  - `HOMEPATH`
  - `KICAD_PTEMPLATES`
  - `KISYS3DMOD`
  - `KISYSMOD`
  - `LOCALAPPDATA`
  - `LOGONSERVER`
  - `NUMBER_OF_PROCESSORS`
  - `ONEDRIVE`
  - `OS`
  - `PATH`
  - `PATHEXT`
  - `PROCESSOR_ARCHITECTURE`
  - `PROCESSOR_ARCHITEW6432`
  - `PROCESSOR_IDENTIFIER`
  - `PROCESSOR_LEVEL`
  - `PROCESSOR_REVISION`
  - `PROGRAMDATA`
  - `PROGRAMFILES`
  - `PROGRAMFILES(X86)`
  - `PROGRAMW6432`
  - `PROMPT`
  - `PSMODULEPATH`
  - `PUBLIC`
  - `SESSIONNAME`
  - `SYSTEMDRIVE`
  - `SYSTEMROOT`
  - `TEMP`
  - `TMP`
  - `USERDOMAIN`
  - `USERDOMAIN_ROAMINGPROFILE`
  - `USERNAME`
  - `USERPROFILE`
  - `VS140COMNTOOLS`
  - `WINDIR`
  - `WORKON_HOME`
  - `PIP_PYTHON_PATH`
  - `PYTHONUNBUFFERED`

Pipenv�specific environment variables:


Debug�specific environment variables:

  - `PATH`: `C:\Program Files (x86)\Python36-32\;C:\Program Files (x86)\Python36-32\Scripts\;C:\Python27\;C:\Python27\Scripts;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\Lenovo\Bluetooth Software\;C:\Program Files\Lenovo\Bluetooth Software\syswow64;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files (x86)\Windows Kits\10\Windows Performance Toolkit\;%localappdata%\Microsoft\WindowsApps;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\130\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\130\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\;C:\Program Files\nodejs\;C:\Program Files\dotnet\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Users\Nelson\AppData\Local\Microsoft\WindowsApps;C:\Users\Nelson\AppData\Roaming\npm;C:\Program Files\Microsoft VS Code\bin;C:\Program Files\Heroku\bin;C:\Users\Nelson\AppData\Local\GitHub\PortableGit_f02737a78695063deace08e96d5042710d3e32db\cmd;C:\Users\Nelson\AppData\Local\GitHubDesktop\bin;%USERPROFILE%\AppData\Local\Microsoft\WindowsApps;`
```

---------------------------



If you're on MacOS, just run the following:

    $ python -m pipenv.help | pbcopy

------------

##### Expected result

Describe what you expected.

Run `pipenv shell` or `pipenv install XXX` in a new folder, and have the venv created and start using the venv right away with the package installed in the venv.

##### Actual result

When possible, provide the verbose output (`--verbose`), especially for locking and dependencies resolving issues.
```
C:\Users\Nelson>cd temp

C:\Users\Nelson\temp>pipenv shell --verbose
Creating a virtualenv for this project…
Using c:\program files (x86)\python36-32\python.exe (3.6.4) to create virtualenv…
Already using interpreter c:\program files (x86)\python36-32\python.exe
Using base prefix 'c:\\program files (x86)\\python36-32'
New python executable in E:\Documents\Envs\temp-fJUtMCm1\Scripts\python.exe
Installing setuptools, pip, wheel...done.

Virtualenv location:
Creating a Pipfile for this project…
Launching subshell in virtual environment. Type 'exit' to return.
Microsoft Windows [Version 10.0.17115.1]
(c) 2017 Microsoft Corporation. All rights reserved.

C:\Users\Nelson\temp>exit

C:\Users\Nelson\temp>pipenv --venv
No virtualenv has been created for this project yet!

C:\Users\Nelson\temp>
```

Running with SET PIPENV_VENV_IN_PROJECT=1 gives a different error message but the same result.

```
C:\Users\Nelson\temp>SET PIPENV_VENV_IN_PROJECT=1

C:\Users\Nelson\temp>pipenv shell
Creating a virtualenv for this project…
Using C:\Program Files (x86)\Python36-32\python.exe (3.6.4) to create virtualenv…
Running virtualenv with interpreter C:\Program Files (x86)\Python36-32\python.exe
Using base prefix 'C:\\Program Files (x86)\\Python36-32'
New python executable in C:\Users\Nelson\temp\.venv\Scripts\python.exe
Installing setuptools, pip, wheel...done.

Virtualenv location: C:\Users\Nelson\temp\.venv
ERROR: Environment '.venv' does not exist. Create it with 'pew new .venv'.

C:\Users\Nelson\temp>pipenv --venv
C:\Users\Nelson\temp\.venv

C:\Users\Nelson\temp>pipenv shell
ERROR: Environment '.venv' does not exist. Create it with 'pew new .venv'.

C:\Users\Nelson\temp>
```

##### Steps to replicate

Provide the steps to replicate (which usually at least includes the commands and the Pipfile).

See actual results above.



Discussion:
this is strange
this is my first time trying out pipenv (I was using virtualenvwrapper before), so let me know if you need any more information or if I should try anything else.

I tried again just now with version 11.6.1 of pipenv with the same result.
@kennethreitz did we drop a `normalize_drive` call somewhere...
Can reproduce. I still need to investigate, but from first glance this is not a `normalize_drive` problem, but the in/out-of project logic is messed up. I’ll try to come up with a fix.
@uranusjr any idea where this was regressed? See also #1689

Resolving patch:
diff --git a/pipenv/patched/pew/pew.py b/pipenv/patched/pew/pew.py
--- a/pipenv/patched/pew/pew.py
+++ b/pipenv/patched/pew/pew.py
@@ -52,8 +52,10 @@
 else:
     default_home = os.path.join(
         os.environ.get('XDG_DATA_HOME', '~/.local/share'), 'virtualenvs')
-workon_home = expandpath(
-    os.environ.get('WORKON_HOME', default_home))
+
+
+def get_workon_home():
+    return expandpath(os.environ.get('WORKON_HOME', default_home))
 
 
 def makedirs_and_symlink_if_needed(workon_home):
@@ -96,7 +98,7 @@ def deploy_completions():
 
 
 def get_project_dir(env):
-    project_file = workon_home / env / '.project'
+    project_file = get_workon_home() / env / '.project'
     if project_file.exists():
         with project_file.open() as f:
             project_dir = f.readline().strip()
@@ -113,7 +115,7 @@ def unsetenv(key):
 
 
 def compute_path(env):
-    envdir = workon_home / env
+    envdir = get_workon_home() / env
     return os.pathsep.join([
         str(envdir / env_bin_dir),
         os.environ['PATH'],
@@ -127,7 +129,7 @@ def inve(env, command, *args, **kwargs):
     # we don't strictly need to restore the environment, since pew runs in
     # its own process, but it feels like the right thing to do
     with temp_environ():
-        os.environ['VIRTUAL_ENV'] = str(workon_home / env)
+        os.environ['VIRTUAL_ENV'] = str(get_workon_home() / env)
         os.environ['PATH'] = compute_path(env)
 
         unsetenv('PYTHONHOME')
@@ -216,7 +218,7 @@ def mkvirtualenv(envname, python=None, packages=[], project=None,
     if python:
         rest = ["--python=%s" % python] + rest
 
-    path = (workon_home / envname).absolute()
+    path = (get_workon_home() / envname).absolute()
 
     try:
         check_call([sys.executable, "-m", "virtualenv", str(path)] + rest)
@@ -265,7 +267,7 @@ def new_cmd(argv):
 def rmvirtualenvs(envs):
     error_happened = False
     for env in envs:
-        env = workon_home / env
+        env = get_workon_home() / env
         if os.environ.get('VIRTUAL_ENV') == str(env):
             err("ERROR: You cannot remove the active environment (%s)." % env)
             error_happened = True
@@ -295,7 +297,7 @@ def packages(site_packages):
 def showvirtualenv(env):
     columns, _ = get_terminal_size()
     pkgs = sorted(packages(sitepackages_dir(env)))
-    env_python = workon_home / env / env_bin_dir / 'python'
+    env_python = get_workon_home() / env / env_bin_dir / 'python'
     l = len(env) + 2
     version = invoke(str(env_python), '-V')
     version = ' - '.join((version.out + version.err).splitlines())
@@ -317,8 +319,8 @@ def show_cmd(argv):
 
 
 def lsenvs():
-    return sorted(set(env.parts[-3] for env in
-                      workon_home.glob(os.path.join('*', env_bin_dir, 'python*'))))
+    items = get_workon_home().glob(os.path.join('*', env_bin_dir, 'python*'))
+    return sorted(set(env.parts[-3] for env in items))
 
 
 def lsvirtualenv(verbose):
@@ -347,7 +349,7 @@ def parse_envname(argv, no_arg_callback):
     env = argv[0]
     if env.startswith('/'):
         sys.exit("ERROR: Invalid environment name '{0}'.".format(env))
-    if not (workon_home / env).exists():
+    if not (get_workon_home() / env).exists():
         sys.exit("ERROR: Environment '{0}' does not exist. Create it with \
 'pew new {0}'.".format(env))
     else:
@@ -372,7 +374,7 @@ def sitepackages_dir(env=os.environ.get('VIRTUAL_ENV')):
     if not env:
         sys.exit('ERROR: no virtualenv active')
     else:
-        env_python = workon_home / env / env_bin_dir / 'python'
+        env_python = get_workon_home() / env / env_bin_dir / 'python'
         return Path(invoke(str(env_python), '-c', 'import distutils; \
 print(distutils.sysconfig.get_python_lib())').out)
 
@@ -459,6 +461,7 @@ def cp_cmd(argv):
 
 def copy_virtualenv_project(source, target):
     source = expandpath(source)
+    workon_home = get_workon_home()
     if not source.exists():
         source = workon_home / source
         if not source.exists():
@@ -490,7 +493,7 @@ def rename_cmd(argv):
 
 def setvirtualenvproject(env, project):
     print('Setting project for {0} to {1}'.format(env, project))
-    with (workon_home / env / '.project').open('wb') as prj:
+    with (get_workon_home() / env / '.project').open('wb') as prj:
         prj.write(str(project).encode())
 
 
@@ -502,7 +505,7 @@ def setproject_cmd(argv):
     env = args.get(0, os.environ.get('VIRTUAL_ENV'))
     if not env:
         sys.exit('pew setproject [virtualenv] [project_path]')
-    if not (workon_home / env).exists():
+    if not (get_workon_home() / env).exists():
         sys.exit("Environment '%s' doesn't exist." % env)
     if not os.path.isdir(project):
         sys.exit('pew setproject: %s does not exist' % project)
@@ -512,7 +515,7 @@ def setproject_cmd(argv):
 def mkproject_cmd(argv):
     """Create a new project directory and its associated virtualenv."""
     if '-l' in argv or '--list' in argv:
-        templates = [t.name[9:] for t in workon_home.glob("template_*")]
+        templates = [t.name[9:] for t in get_workon_home().glob("template_*")]
         print("Available project templates:", *templates, sep='\n')
         return
 
@@ -542,7 +545,7 @@ def mkproject_cmd(argv):
     project.mkdir()
 
     for template_name in args.templates:
-        template = workon_home / ("template_" + template_name)
+        template = get_workon_home() / ("template_" + template_name)
         inve(args.envname, str(template), args.envname, str(project))
     if args.activate:
         shell(args.envname, cwd=str(project))
@@ -552,7 +555,7 @@ def mktmpenv_cmd(argv):
     """Create a temporary virtualenv."""
     parser = mkvirtualenv_argparser()
     env = '.'
-    while (workon_home / env).exists():
+    while (get_workon_home() / env).exists():
         env = hex(random.getrandbits(64))[2:-1]
 
     args, rest = parser.parse_known_args(argv)
@@ -574,10 +577,10 @@ def wipeenv_cmd(argv):
 
     if not env:
         sys.exit('ERROR: no virtualenv active')
-    elif not (workon_home / env).exists():
+    elif not (get_workon_home() / env).exists():
         sys.exit("ERROR: Environment '{0}' does not exist.".format(env))
     else:
-        env_pip = str(workon_home / env / env_bin_dir / 'pip')
+        env_pip = str(get_workon_home() / env / env_bin_dir / 'pip')
         all_pkgs = set(invoke(env_pip, 'freeze').out.splitlines())
         pkgs = set(p for p in all_pkgs if len(p.split("==")) == 2)
         ignored = sorted(all_pkgs - pkgs)
@@ -623,7 +626,7 @@ def restore_cmd(argv):
         sys.exit('You must provide a valid virtualenv to target')
 
     env = argv[0]
-    path = workon_home / env
+    path = get_workon_home() / env
     py = path / env_bin_dir / ('python.exe' if windows else 'python')
     exact_py = py.resolve().name
 
@@ -633,7 +636,7 @@ def restore_cmd(argv):
 def dir_cmd(argv):
     """Print the path for the virtualenv directory"""
     env = parse_envname(argv, lambda : sys.exit('You must provide a valid virtualenv to target'))
-    print(workon_home / env)
+    print(get_workon_home() / env)
 
 
 def install_cmd(argv):
@@ -745,7 +748,7 @@ def print_commands(cmds):
 
 
 def pew():
-    first_run = makedirs_and_symlink_if_needed(workon_home)
+    first_run = makedirs_and_symlink_if_needed(get_workon_home())
     if first_run and sys.stdin.isatty():
         first_run_setup()
 


Test patch: