2 /* Return the initial module search path. */
3 /* Used by DOS, OS/2, Windows 3.1, Windows 95/98, Windows NT. */
5 /* ----------------------------------------------------------------
6 PATH RULES FOR WINDOWS:
7 This describes how sys.path is formed on Windows. It describes the
8 functionality, not the implementation (ie, the order in which these
9 are actually fetched is different)
11 * Python always adds an empty entry at the start, which corresponds
12 to the current directory.
14 * If the PYTHONPATH env. var. exists, its entries are added next.
16 * We look in the registry for "application paths" - that is, sub-keys
17 under the main PythonPath registry key. These are added next (the
18 order of sub-key processing is undefined).
19 HKEY_CURRENT_USER is searched and added first.
20 HKEY_LOCAL_MACHINE is searched and added next.
21 (Note that all known installers only use HKLM, so HKCU is typically
24 * We attempt to locate the "Python Home" - if the PYTHONHOME env var
25 is set, we believe it. Otherwise, we use the path of our host .EXE's
26 to try and locate our "landmark" (lib\\os.py) and deduce our home.
27 - If we DO have a Python Home: The relevant sub-directories (Lib,
28 plat-win, lib-tk, etc) are based on the Python Home
29 - If we DO NOT have a Python Home, the core Python Path is
30 loaded from the registry. This is the main PythonPath key,
31 and both HKLM and HKCU are combined to form the path)
33 * Iff - we can not locate the Python Home, have not had a PYTHONPATH
34 specified, and can't locate any Registry entries (ie, we have _nothing_
35 we can assume is a good path), a default path with relative entries is
36 used (eg. .\Lib;.\plat-win, etc)
39 The end result of all this is:
40 * When running python.exe, or any other .exe in the main Python directory
41 (either an installed version, or directly from the PCbuild directory),
42 the core path is deduced, and the core paths in the registry are
43 ignored. Other "application paths" in the registry are always read.
45 * When Python is hosted in another exe (different directory, embedded via
46 COM, etc), the Python Home will not be deduced, so the core path from
47 the registry is used. Other "application paths" in the registry are
50 * If Python can't find its home and there is no registry (eg, frozen
51 exe, some very strange installation setup) you get a path with
52 some default, but relative, paths.
54 ---------------------------------------------------------------- */
65 #include <sys/types.h>
69 /* Search in some common locations for the associated Python libraries.
71 * Py_GetPath() tries to return a sensible Python module search path.
73 * The approach is an adaptation for Windows of the strategy used in
74 * ../Modules/getpath.c; it uses the Windows Registry as one of its
75 * information sources.
79 #define LANDMARK "lib\\os.py"
82 static char prefix
[MAXPATHLEN
+1];
83 static char progpath
[MAXPATHLEN
+1];
84 static char dllpath
[MAXPATHLEN
+1];
85 static char *module_search_path
= NULL
;
89 is_sep(char ch
) /* determine if "ch" is a separator character */
92 return ch
== SEP
|| ch
== ALTSEP
;
98 /* assumes 'dir' null terminated in bounds. Never writes
99 beyond existing terminator.
104 size_t i
= strlen(dir
);
105 while (i
> 0 && !is_sep(dir
[i
]))
112 exists(char *filename
)
115 return stat(filename
, &buf
) == 0;
118 /* Assumes 'filename' MAXPATHLEN+1 bytes long -
119 may extend 'filename' by one character.
122 ismodule(char *filename
) /* Is module -- check for .pyc/.pyo too */
124 if (exists(filename
))
127 /* Check for the compiled version of prefix. */
128 if (strlen(filename
) < MAXPATHLEN
) {
129 strcat(filename
, Py_OptimizeFlag
? "o" : "c");
130 if (exists(filename
))
136 /* Add a path component, by appending stuff to buffer.
137 buffer must have at least MAXPATHLEN + 1 bytes allocated, and contain a
138 NUL-terminated string with no more than MAXPATHLEN characters (not counting
139 the trailing NUL). It's a fatal error if it contains a string longer than
140 that (callers must be careful!). If these requirements are met, it's
141 guaranteed that buffer will still be a NUL-terminated string with no more
142 than MAXPATHLEN characters at exit. If stuff is too long, only as much of
143 stuff as fits will be appended.
146 join(char *buffer
, char *stuff
)
149 if (is_sep(stuff
[0]))
153 if (n
> 0 && !is_sep(buffer
[n
-1]) && n
< MAXPATHLEN
)
157 Py_FatalError("buffer overflow in getpathp.c's joinpath()");
159 if (n
+ k
> MAXPATHLEN
)
161 strncpy(buffer
+n
, stuff
, k
);
165 /* gotlandmark only called by search_for_prefix, which ensures
166 'prefix' is null terminated in bounds. join() ensures
167 'landmark' can not overflow prefix if too long.
170 gotlandmark(char *landmark
)
176 join(prefix
, landmark
);
177 ok
= ismodule(prefix
);
182 /* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd.
183 assumption provided by only caller, calculate_path() */
185 search_for_prefix(char *argv0_path
, char *landmark
)
187 /* Search from argv0_path, until landmark is found */
188 strcpy(prefix
, argv0_path
);
190 if (gotlandmark(landmark
))
199 /* a string loaded from the DLL at startup.*/
200 extern const char *PyWin_DLLVersionString
;
203 /* Load a PYTHONPATH value from the registry.
204 Load from either HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER.
206 Works in both Unicode and 8bit environments. Only uses the
207 Ex family of functions so it also works with Windows CE.
209 Returns NULL, or a pointer that should be freed.
211 XXX - this code is pretty strange, as it used to also
212 work on Win16, where the buffer sizes werent available
213 in advance. It could be simplied now Win16/Win32s is dead!
217 getpythonregpath(HKEY keyBase
, int skipcore
)
224 TCHAR
*dataBuf
= NULL
;
225 static const TCHAR keyPrefix
[] = _T("Software\\Python\\PythonCore\\");
226 static const TCHAR keySuffix
[] = _T("\\PythonPath");
229 TCHAR
*keyBuf
= NULL
;
231 TCHAR
**ppPaths
= NULL
;
233 /* Tried to use sysget("winver") but here is too early :-( */
234 versionLen
= _tcslen(PyWin_DLLVersionString
);
235 /* Space for all the chars, plus one \0 */
236 keyBuf
= keyBufPtr
= malloc(sizeof(keyPrefix
) +
237 sizeof(TCHAR
)*(versionLen
-1) +
239 if (keyBuf
==NULL
) goto done
;
241 memcpy(keyBufPtr
, keyPrefix
, sizeof(keyPrefix
)-sizeof(TCHAR
));
242 keyBufPtr
+= sizeof(keyPrefix
)/sizeof(TCHAR
) - 1;
243 memcpy(keyBufPtr
, PyWin_DLLVersionString
, versionLen
* sizeof(TCHAR
));
244 keyBufPtr
+= versionLen
;
245 /* NULL comes with this one! */
246 memcpy(keyBufPtr
, keySuffix
, sizeof(keySuffix
));
247 /* Open the root Python key */
248 rc
=RegOpenKeyEx(keyBase
,
253 if (rc
!=ERROR_SUCCESS
) goto done
;
254 /* Find out how big our core buffer is, and how many subkeys we have */
255 rc
= RegQueryInfoKey(newKey
, NULL
, NULL
, NULL
, &numKeys
, NULL
, NULL
,
256 NULL
, NULL
, &dataSize
, NULL
, NULL
);
257 if (rc
!=ERROR_SUCCESS
) goto done
;
258 if (skipcore
) dataSize
= 0; /* Only count core ones if we want them! */
259 /* Allocate a temp array of char buffers, so we only need to loop
260 reading the registry once
262 ppPaths
= malloc( sizeof(TCHAR
*) * numKeys
);
263 if (ppPaths
==NULL
) goto done
;
264 memset(ppPaths
, 0, sizeof(TCHAR
*) * numKeys
);
265 /* Loop over all subkeys, allocating a temp sub-buffer. */
266 for(index
=0;index
<numKeys
;index
++) {
267 TCHAR keyBuf
[MAX_PATH
+1];
269 DWORD reqdSize
= MAX_PATH
+1;
270 /* Get the sub-key name */
271 DWORD rc
= RegEnumKeyEx(newKey
, index
, keyBuf
, &reqdSize
,
272 NULL
, NULL
, NULL
, NULL
);
273 if (rc
!=ERROR_SUCCESS
) goto done
;
274 /* Open the sub-key */
275 rc
=RegOpenKeyEx(newKey
,
280 if (rc
!=ERROR_SUCCESS
) goto done
;
281 /* Find the value of the buffer size, malloc, then read it */
282 RegQueryValueEx(subKey
, NULL
, 0, NULL
, NULL
, &reqdSize
);
284 ppPaths
[index
] = malloc(reqdSize
);
285 if (ppPaths
[index
]) {
286 RegQueryValueEx(subKey
, NULL
, 0, NULL
,
287 (LPBYTE
)ppPaths
[index
],
289 dataSize
+= reqdSize
+ 1; /* 1 for the ";" */
294 /* original datasize from RegQueryInfo doesn't include the \0 */
295 dataBuf
= malloc((dataSize
+1) * sizeof(TCHAR
));
297 TCHAR
*szCur
= dataBuf
;
298 DWORD reqdSize
= dataSize
;
299 /* Copy our collected strings */
300 for (index
=0;index
<numKeys
;index
++) {
302 *(szCur
++) = _T(';');
305 if (ppPaths
[index
]) {
306 Py_ssize_t len
= _tcslen(ppPaths
[index
]);
307 _tcsncpy(szCur
, ppPaths
[index
], len
);
309 assert(dataSize
> (DWORD
)len
);
310 dataSize
-= (DWORD
)len
;
316 /* If we have no values, we dont need a ';' */
318 *(szCur
++) = _T(';');
321 /* Now append the core path entries -
322 this will include the NULL
324 rc
= RegQueryValueEx(newKey
, NULL
, 0, NULL
,
325 (LPBYTE
)szCur
, &dataSize
);
327 /* And set the result - caller must free
328 If MBCS, it is fine as is. If Unicode, allocate new
332 retval
= (char *)malloc(reqdSize
+1);
334 WideCharToMultiByte(CP_ACP
, 0,
335 dataBuf
, -1, /* source */
336 retval
, reqdSize
+1, /* dest */
344 /* Loop freeing my temp buffers */
346 for(index
=0;index
<numKeys
;index
++)
347 if (ppPaths
[index
]) free(ppPaths
[index
]);
356 #endif /* MS_WINDOWS */
361 extern char *Py_GetProgramName(void);
362 char *path
= getenv("PATH");
363 char *prog
= Py_GetProgramName();
366 extern HANDLE PyWin_DLLhModule
;
368 WCHAR wprogpath
[MAXPATHLEN
+1];
369 /* Windows documents that GetModuleFileName() will "truncate",
370 but makes no mention of the null terminator. Play it safe.
371 PLUS Windows itself defines MAX_PATH as the same, but anyway...
373 wprogpath
[MAXPATHLEN
]=_T('\0');
374 if (PyWin_DLLhModule
&&
375 GetModuleFileName(PyWin_DLLhModule
, wprogpath
, MAXPATHLEN
)) {
376 WideCharToMultiByte(CP_ACP
, 0,
378 dllpath
, MAXPATHLEN
+1,
381 wprogpath
[MAXPATHLEN
]=_T('\0');
382 if (GetModuleFileName(NULL
, wprogpath
, MAXPATHLEN
)) {
383 WideCharToMultiByte(CP_ACP
, 0,
385 progpath
, MAXPATHLEN
+1,
390 /* static init of progpath ensures final char remains \0 */
391 if (PyWin_DLLhModule
)
392 if (!GetModuleFileName(PyWin_DLLhModule
, dllpath
, MAXPATHLEN
))
394 if (GetModuleFileName(NULL
, progpath
, MAXPATHLEN
))
398 if (prog
== NULL
|| *prog
== '\0')
401 /* If there is no slash in the argv0 path, then we have to
402 * assume python is on the user's $PATH, since there's no
403 * other way to find a directory to start the search from. If
404 * $PATH isn't exported, you lose.
407 if (strchr(prog
, SEP
) || strchr(prog
, ALTSEP
))
409 if (strchr(prog
, SEP
))
411 strncpy(progpath
, prog
, MAXPATHLEN
);
414 char *delim
= strchr(path
, DELIM
);
417 size_t len
= delim
- path
;
418 /* ensure we can't overwrite buffer */
419 len
= min(MAXPATHLEN
,len
);
420 strncpy(progpath
, path
, len
);
421 *(progpath
+ len
) = '\0';
424 strncpy(progpath
, path
, MAXPATHLEN
);
426 /* join() is safe for MAXPATHLEN+1 size buffer */
427 join(progpath
, prog
);
428 if (exists(progpath
))
445 char argv0_path
[MAXPATHLEN
+1];
448 char *pythonhome
= Py_GetPythonHome();
449 char *envpath
= Py_GETENV("PYTHONPATH");
452 int skiphome
, skipdefault
;
453 char *machinepath
= NULL
;
454 char *userpath
= NULL
;
455 char zip_path
[MAXPATHLEN
+1];
460 /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */
461 strcpy(argv0_path
, progpath
);
463 if (pythonhome
== NULL
|| *pythonhome
== '\0') {
464 if (search_for_prefix(argv0_path
, LANDMARK
))
470 strncpy(prefix
, pythonhome
, MAXPATHLEN
);
472 if (envpath
&& *envpath
== '\0')
477 /* Calculate zip archive path */
478 if (dllpath
[0]) /* use name of python DLL */
479 strncpy(zip_path
, dllpath
, MAXPATHLEN
);
480 else /* use name of executable program */
481 strncpy(zip_path
, progpath
, MAXPATHLEN
);
482 zip_path
[MAXPATHLEN
] = '\0';
483 len
= strlen(zip_path
);
485 zip_path
[len
-3] = 'z'; /* change ending to "zip" */
486 zip_path
[len
-2] = 'i';
487 zip_path
[len
-1] = 'p';
493 skiphome
= pythonhome
==NULL
? 0 : 1;
494 machinepath
= getpythonregpath(HKEY_LOCAL_MACHINE
, skiphome
);
495 userpath
= getpythonregpath(HKEY_CURRENT_USER
, skiphome
);
496 /* We only use the default relative PYTHONPATH if we havent
497 anything better to use! */
498 skipdefault
= envpath
!=NULL
|| pythonhome
!=NULL
|| \
499 machinepath
!=NULL
|| userpath
!=NULL
;
502 /* We need to construct a path from the following parts.
503 (1) the PYTHONPATH environment variable, if set;
504 (2) for Win32, the zip archive file path;
505 (3) for Win32, the machinepath and userpath, if set;
506 (4) the PYTHONPATH config macro, with the leading "."
507 of each component replaced with pythonhome, if set;
508 (5) the directory containing the executable (argv0_path).
509 The length calculation calculates #4 first.
511 - If PYTHONHOME is set (in any way) item (3) is ignored.
512 - If registry values are used, (4) and (5) are ignored.
515 /* Calculate size of return buffer */
516 if (pythonhome
!= NULL
) {
519 for (p
= PYTHONPATH
; *p
; p
++) {
521 bufsz
++; /* number of DELIM plus one */
523 bufsz
*= strlen(pythonhome
);
527 bufsz
+= strlen(PYTHONPATH
) + 1;
528 bufsz
+= strlen(argv0_path
) + 1;
531 bufsz
+= strlen(userpath
) + 1;
533 bufsz
+= strlen(machinepath
) + 1;
534 bufsz
+= strlen(zip_path
) + 1;
537 bufsz
+= strlen(envpath
) + 1;
539 module_search_path
= buf
= malloc(bufsz
);
541 /* We can't exit, so print a warning and limp along */
542 fprintf(stderr
, "Can't malloc dynamic PYTHONPATH.\n");
544 fprintf(stderr
, "Using environment $PYTHONPATH.\n");
545 module_search_path
= envpath
;
548 fprintf(stderr
, "Using default static path.\n");
549 module_search_path
= PYTHONPATH
;
556 #endif /* MS_WINDOWS */
561 strcpy(buf
, envpath
);
562 buf
= strchr(buf
, '\0');
567 strcpy(buf
, zip_path
);
568 buf
= strchr(buf
, '\0');
572 strcpy(buf
, userpath
);
573 buf
= strchr(buf
, '\0');
578 strcpy(buf
, machinepath
);
579 buf
= strchr(buf
, '\0');
583 if (pythonhome
== NULL
) {
585 strcpy(buf
, PYTHONPATH
);
586 buf
= strchr(buf
, '\0');
590 if (pythonhome
== NULL
) {
591 strcpy(buf
, PYTHONPATH
);
592 buf
= strchr(buf
, '\0');
594 #endif /* MS_WINDOWS */
596 char *p
= PYTHONPATH
;
600 q
= strchr(p
, DELIM
);
605 if (p
[0] == '.' && is_sep(p
[1])) {
606 strcpy(buf
, pythonhome
);
607 buf
= strchr(buf
, '\0');
621 strcpy(buf
, argv0_path
);
622 buf
= strchr(buf
, '\0');
625 /* Now to pull one last hack/trick. If sys.prefix is
626 empty, then try and find it somewhere on the paths
627 we calculated. We scan backwards, as our general policy
628 is that Python core directories are at the *end* of
629 sys.path. We assume that our "lib" directory is
630 on the path, and that our 'prefix' directory is
634 char lookBuf
[MAXPATHLEN
+1];
635 char *look
= buf
- 1; /* 'buf' is at the end of the buffer */
638 char *lookEnd
= look
;
639 /* 'look' will end up one character before the
640 start of the path in question - even if this
641 is one character before the start of the buffer
643 while (*look
!= DELIM
&& look
>= module_search_path
)
645 nchars
= lookEnd
-look
;
646 strncpy(lookBuf
, look
+1, nchars
);
647 lookBuf
[nchars
] = '\0';
648 /* Up one level to the parent */
650 if (search_for_prefix(lookBuf
, LANDMARK
)) {
653 /* If we are out of paths to search - give up */
654 if (look
< module_search_path
)
662 /* External interface */
667 if (!module_search_path
)
669 return module_search_path
;
675 if (!module_search_path
)
681 Py_GetExecPrefix(void)
683 return Py_GetPrefix();
687 Py_GetProgramFullPath(void)
689 if (!module_search_path
)