@@ -384,6 +384,31 @@ find_python_by_version(wchar_t const * wanted_ver)
384384}
385385
386386
387+ static wchar_t *
388+ find_python_by_venv ()
389+ {
390+ static wchar_t venv_python [MAX_PATH ];
391+ wchar_t * virtual_env = get_env (L"VIRTUAL_ENV" );
392+ DWORD attrs ;
393+
394+ /* Check for VIRTUAL_ENV environment variable */
395+ if (virtual_env == NULL || virtual_env [0 ] == L'\0' ) {
396+ return NULL ;
397+ }
398+
399+ /* Check for a python executable in the venv */
400+ debug (L"Checking for Python executable in virtual env '%ls'\n" , virtual_env );
401+ _snwprintf_s (venv_python , MAX_PATH , _TRUNCATE ,
402+ L"%ls\\Scripts\\%ls" , virtual_env , PYTHON_EXECUTABLE );
403+ attrs = GetFileAttributesW (venv_python );
404+ if (attrs == INVALID_FILE_ATTRIBUTES ) {
405+ debug (L"Python executable %ls missing from virtual env\n" , venv_python );
406+ return NULL ;
407+ }
408+
409+ return venv_python ;
410+ }
411+
387412static wchar_t appdata_ini_path [MAX_PATH ];
388413static wchar_t launcher_ini_path [MAX_PATH ];
389414
@@ -1309,6 +1334,7 @@ process(int argc, wchar_t ** argv)
13091334{
13101335 wchar_t * wp ;
13111336 wchar_t * command ;
1337+ wchar_t * executable ;
13121338 wchar_t * p ;
13131339 int rc = 0 ;
13141340 size_t plen ;
@@ -1453,6 +1479,7 @@ process(int argc, wchar_t ** argv)
14531479 if (ip == NULL )
14541480 error (RC_NO_PYTHON , L"Requested Python version (%ls) not \
14551481installed" , & p [1 ]);
1482+ executable = ip -> executable ;
14561483 command += wcslen (p );
14571484 command = skip_whitespace (command );
14581485 }
@@ -1470,9 +1497,16 @@ installed", &p[1]);
14701497#endif
14711498
14721499 if (!valid ) {
1473- ip = locate_python (L"" );
1474- if (ip == NULL )
1475- error (RC_NO_PYTHON , L"Can't find a default Python." );
1500+ /* Look for an active virtualenv */
1501+ executable = find_python_by_venv ();
1502+
1503+ /* If we didn't find one, look for the default Python */
1504+ if (executable == NULL ) {
1505+ ip = locate_python (L"" );
1506+ if (ip == NULL )
1507+ error (RC_NO_PYTHON , L"Can't find a default Python." );
1508+ executable = ip -> executable ;
1509+ }
14761510 if ((argc == 2 ) && (!_wcsicmp (p , L"-h" ) || !_wcsicmp (p , L"--help" ))) {
14771511#if defined(_M_X64 )
14781512 BOOL canDo64bit = TRUE;
@@ -1500,7 +1534,7 @@ Launcher arguments:\n\n\
15001534 fflush (stdout );
15011535 }
15021536 }
1503- invoke_child (ip -> executable , NULL , command );
1537+ invoke_child (executable , NULL , command );
15041538 return rc ;
15051539}
15061540
0 commit comments