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 #ifdef HAVE_SYS_TYPES_H
66 #include <sys/types.h>
67 #endif /* HAVE_SYS_TYPES_H */
69 #ifdef HAVE_SYS_STAT_H
71 #endif /* HAVE_SYS_STAT_H */
75 /* Search in some common locations for the associated Python libraries.
77 * Py_GetPath() tries to return a sensible Python module search path.
79 * The approach is an adaptation for Windows of the strategy used in
80 * ../Modules/getpath.c; it uses the Windows Registry as one of its
81 * information sources.
85 #define LANDMARK "lib\\os.py"
88 static char prefix
[MAXPATHLEN
+1];
89 static char progpath
[MAXPATHLEN
+1];
90 static char dllpath
[MAXPATHLEN
+1];
91 static char *module_search_path
= NULL
;
95 is_sep(char ch
) /* determine if "ch" is a separator character */
98 return ch
== SEP
|| ch
== ALTSEP
;
104 /* assumes 'dir' null terminated in bounds. Never writes
105 beyond existing terminator.
110 size_t i
= strlen(dir
);
111 while (i
> 0 && !is_sep(dir
[i
]))
118 exists(char *filename
)
121 return stat(filename
, &buf
) == 0;
124 /* Assumes 'filename' MAXPATHLEN+1 bytes long -
125 may extend 'filename' by one character.
128 ismodule(char *filename
) /* Is module -- check for .pyc/.pyo too */
130 if (exists(filename
))
133 /* Check for the compiled version of prefix. */
134 if (strlen(filename
) < MAXPATHLEN
) {
135 strcat(filename
, Py_OptimizeFlag
? "o" : "c");
136 if (exists(filename
))
142 /* Add a path component, by appending stuff to buffer.
143 buffer must have at least MAXPATHLEN + 1 bytes allocated, and contain a
144 NUL-terminated string with no more than MAXPATHLEN characters (not counting
145 the trailing NUL). It's a fatal error if it contains a string longer than
146 that (callers must be careful!). If these requirements are met, it's
147 guaranteed that buffer will still be a NUL-terminated string with no more
148 than MAXPATHLEN characters at exit. If stuff is too long, only as much of
149 stuff as fits will be appended.
152 join(char *buffer
, char *stuff
)
155 if (is_sep(stuff
[0]))
159 if (n
> 0 && !is_sep(buffer
[n
-1]) && n
< MAXPATHLEN
)
163 Py_FatalError("buffer overflow in getpathp.c's joinpath()");
165 if (n
+ k
> MAXPATHLEN
)
167 strncpy(buffer
+n
, stuff
, k
);
171 /* gotlandmark only called by search_for_prefix, which ensures
172 'prefix' is null terminated in bounds. join() ensures
173 'landmark' can not overflow prefix if too long.
176 gotlandmark(char *landmark
)
182 join(prefix
, landmark
);
183 ok
= ismodule(prefix
);
188 /* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd.
189 assumption provided by only caller, calculate_path() */
191 search_for_prefix(char *argv0_path
, char *landmark
)
193 /* Search from argv0_path, until landmark is found */
194 strcpy(prefix
, argv0_path
);
196 if (gotlandmark(landmark
))
205 /* a string loaded from the DLL at startup.*/
206 extern const char *PyWin_DLLVersionString
;
209 /* Load a PYTHONPATH value from the registry.
210 Load from either HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER.
212 Works in both Unicode and 8bit environments. Only uses the
213 Ex family of functions so it also works with Windows CE.
215 Returns NULL, or a pointer that should be freed.
217 XXX - this code is pretty strange, as it used to also
218 work on Win16, where the buffer sizes werent available
219 in advance. It could be simplied now Win16/Win32s is dead!
223 getpythonregpath(HKEY keyBase
, int skipcore
)
230 TCHAR
*dataBuf
= NULL
;
231 static const TCHAR keyPrefix
[] = _T("Software\\Python\\PythonCore\\");
232 static const TCHAR keySuffix
[] = _T("\\PythonPath");
235 TCHAR
*keyBuf
= NULL
;
237 TCHAR
**ppPaths
= NULL
;
239 /* Tried to use sysget("winver") but here is too early :-( */
240 versionLen
= _tcslen(PyWin_DLLVersionString
);
241 /* Space for all the chars, plus one \0 */
242 keyBuf
= keyBufPtr
= malloc(sizeof(keyPrefix
) +
243 sizeof(TCHAR
)*(versionLen
-1) +
245 if (keyBuf
==NULL
) goto done
;
247 memcpy(keyBufPtr
, keyPrefix
, sizeof(keyPrefix
)-sizeof(TCHAR
));
248 keyBufPtr
+= sizeof(keyPrefix
)/sizeof(TCHAR
) - 1;
249 memcpy(keyBufPtr
, PyWin_DLLVersionString
, versionLen
* sizeof(TCHAR
));
250 keyBufPtr
+= versionLen
;
251 /* NULL comes with this one! */
252 memcpy(keyBufPtr
, keySuffix
, sizeof(keySuffix
));
253 /* Open the root Python key */
254 rc
=RegOpenKeyEx(keyBase
,
259 if (rc
!=ERROR_SUCCESS
) goto done
;
260 /* Find out how big our core buffer is, and how many subkeys we have */
261 rc
= RegQueryInfoKey(newKey
, NULL
, NULL
, NULL
, &numKeys
, NULL
, NULL
,
262 NULL
, NULL
, &dataSize
, NULL
, NULL
);
263 if (rc
!=ERROR_SUCCESS
) goto done
;
264 if (skipcore
) dataSize
= 0; /* Only count core ones if we want them! */
265 /* Allocate a temp array of char buffers, so we only need to loop
266 reading the registry once
268 ppPaths
= malloc( sizeof(TCHAR
*) * numKeys
);
269 if (ppPaths
==NULL
) goto done
;
270 memset(ppPaths
, 0, sizeof(TCHAR
*) * numKeys
);
271 /* Loop over all subkeys, allocating a temp sub-buffer. */
272 for(index
=0;index
<numKeys
;index
++) {
273 TCHAR keyBuf
[MAX_PATH
+1];
275 DWORD reqdSize
= MAX_PATH
+1;
276 /* Get the sub-key name */
277 DWORD rc
= RegEnumKeyEx(newKey
, index
, keyBuf
, &reqdSize
,
278 NULL
, NULL
, NULL
, NULL
);
279 if (rc
!=ERROR_SUCCESS
) goto done
;
280 /* Open the sub-key */
281 rc
=RegOpenKeyEx(newKey
,
286 if (rc
!=ERROR_SUCCESS
) goto done
;
287 /* Find the value of the buffer size, malloc, then read it */
288 RegQueryValueEx(subKey
, NULL
, 0, NULL
, NULL
, &reqdSize
);
290 ppPaths
[index
] = malloc(reqdSize
);
291 if (ppPaths
[index
]) {
292 RegQueryValueEx(subKey
, NULL
, 0, NULL
,
293 (LPBYTE
)ppPaths
[index
],
295 dataSize
+= reqdSize
+ 1; /* 1 for the ";" */
301 /* return null if no path to return */
302 if (dataSize
== 0) goto done
;
304 /* original datasize from RegQueryInfo doesn't include the \0 */
305 dataBuf
= malloc((dataSize
+1) * sizeof(TCHAR
));
307 TCHAR
*szCur
= dataBuf
;
308 DWORD reqdSize
= dataSize
;
309 /* Copy our collected strings */
310 for (index
=0;index
<numKeys
;index
++) {
312 *(szCur
++) = _T(';');
315 if (ppPaths
[index
]) {
316 Py_ssize_t len
= _tcslen(ppPaths
[index
]);
317 _tcsncpy(szCur
, ppPaths
[index
], len
);
319 assert(dataSize
> (DWORD
)len
);
320 dataSize
-= (DWORD
)len
;
326 /* If we have no values, we dont need a ';' */
328 *(szCur
++) = _T(';');
331 /* Now append the core path entries -
332 this will include the NULL
334 rc
= RegQueryValueEx(newKey
, NULL
, 0, NULL
,
335 (LPBYTE
)szCur
, &dataSize
);
337 /* And set the result - caller must free
338 If MBCS, it is fine as is. If Unicode, allocate new
342 retval
= (char *)malloc(reqdSize
+1);
344 WideCharToMultiByte(CP_ACP
, 0,
345 dataBuf
, -1, /* source */
346 retval
, reqdSize
+1, /* dest */
354 /* Loop freeing my temp buffers */
356 for(index
=0;index
<numKeys
;index
++)
357 if (ppPaths
[index
]) free(ppPaths
[index
]);
366 #endif /* MS_WINDOWS */
371 extern char *Py_GetProgramName(void);
372 char *path
= getenv("PATH");
373 char *prog
= Py_GetProgramName();
376 extern HANDLE PyWin_DLLhModule
;
378 WCHAR wprogpath
[MAXPATHLEN
+1];
379 /* Windows documents that GetModuleFileName() will "truncate",
380 but makes no mention of the null terminator. Play it safe.
381 PLUS Windows itself defines MAX_PATH as the same, but anyway...
383 wprogpath
[MAXPATHLEN
]=_T('\0');
384 if (PyWin_DLLhModule
&&
385 GetModuleFileName(PyWin_DLLhModule
, wprogpath
, MAXPATHLEN
)) {
386 WideCharToMultiByte(CP_ACP
, 0,
388 dllpath
, MAXPATHLEN
+1,
391 wprogpath
[MAXPATHLEN
]=_T('\0');
392 if (GetModuleFileName(NULL
, wprogpath
, MAXPATHLEN
)) {
393 WideCharToMultiByte(CP_ACP
, 0,
395 progpath
, MAXPATHLEN
+1,
400 /* static init of progpath ensures final char remains \0 */
401 if (PyWin_DLLhModule
)
402 if (!GetModuleFileName(PyWin_DLLhModule
, dllpath
, MAXPATHLEN
))
404 if (GetModuleFileName(NULL
, progpath
, MAXPATHLEN
))
408 if (prog
== NULL
|| *prog
== '\0')
411 /* If there is no slash in the argv0 path, then we have to
412 * assume python is on the user's $PATH, since there's no
413 * other way to find a directory to start the search from. If
414 * $PATH isn't exported, you lose.
417 if (strchr(prog
, SEP
) || strchr(prog
, ALTSEP
))
419 if (strchr(prog
, SEP
))
421 strncpy(progpath
, prog
, MAXPATHLEN
);
424 char *delim
= strchr(path
, DELIM
);
427 size_t len
= delim
- path
;
428 /* ensure we can't overwrite buffer */
429 len
= min(MAXPATHLEN
,len
);
430 strncpy(progpath
, path
, len
);
431 *(progpath
+ len
) = '\0';
434 strncpy(progpath
, path
, MAXPATHLEN
);
436 /* join() is safe for MAXPATHLEN+1 size buffer */
437 join(progpath
, prog
);
438 if (exists(progpath
))
455 char argv0_path
[MAXPATHLEN
+1];
458 char *pythonhome
= Py_GetPythonHome();
459 char *envpath
= Py_GETENV("PYTHONPATH");
462 int skiphome
, skipdefault
;
463 char *machinepath
= NULL
;
464 char *userpath
= NULL
;
465 char zip_path
[MAXPATHLEN
+1];
470 /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */
471 strcpy(argv0_path
, progpath
);
473 if (pythonhome
== NULL
|| *pythonhome
== '\0') {
474 if (search_for_prefix(argv0_path
, LANDMARK
))
480 strncpy(prefix
, pythonhome
, MAXPATHLEN
);
482 if (envpath
&& *envpath
== '\0')
487 /* Calculate zip archive path */
488 if (dllpath
[0]) /* use name of python DLL */
489 strncpy(zip_path
, dllpath
, MAXPATHLEN
);
490 else /* use name of executable program */
491 strncpy(zip_path
, progpath
, MAXPATHLEN
);
492 zip_path
[MAXPATHLEN
] = '\0';
493 len
= strlen(zip_path
);
495 zip_path
[len
-3] = 'z'; /* change ending to "zip" */
496 zip_path
[len
-2] = 'i';
497 zip_path
[len
-1] = 'p';
503 skiphome
= pythonhome
==NULL
? 0 : 1;
504 machinepath
= getpythonregpath(HKEY_LOCAL_MACHINE
, skiphome
);
505 userpath
= getpythonregpath(HKEY_CURRENT_USER
, skiphome
);
506 /* We only use the default relative PYTHONPATH if we havent
507 anything better to use! */
508 skipdefault
= envpath
!=NULL
|| pythonhome
!=NULL
|| \
509 machinepath
!=NULL
|| userpath
!=NULL
;
512 /* We need to construct a path from the following parts.
513 (1) the PYTHONPATH environment variable, if set;
514 (2) for Win32, the zip archive file path;
515 (3) for Win32, the machinepath and userpath, if set;
516 (4) the PYTHONPATH config macro, with the leading "."
517 of each component replaced with pythonhome, if set;
518 (5) the directory containing the executable (argv0_path).
519 The length calculation calculates #4 first.
521 - If PYTHONHOME is set (in any way) item (3) is ignored.
522 - If registry values are used, (4) and (5) are ignored.
525 /* Calculate size of return buffer */
526 if (pythonhome
!= NULL
) {
529 for (p
= PYTHONPATH
; *p
; p
++) {
531 bufsz
++; /* number of DELIM plus one */
533 bufsz
*= strlen(pythonhome
);
537 bufsz
+= strlen(PYTHONPATH
) + 1;
538 bufsz
+= strlen(argv0_path
) + 1;
541 bufsz
+= strlen(userpath
) + 1;
543 bufsz
+= strlen(machinepath
) + 1;
544 bufsz
+= strlen(zip_path
) + 1;
547 bufsz
+= strlen(envpath
) + 1;
549 module_search_path
= buf
= malloc(bufsz
);
551 /* We can't exit, so print a warning and limp along */
552 fprintf(stderr
, "Can't malloc dynamic PYTHONPATH.\n");
554 fprintf(stderr
, "Using environment $PYTHONPATH.\n");
555 module_search_path
= envpath
;
558 fprintf(stderr
, "Using default static path.\n");
559 module_search_path
= PYTHONPATH
;
566 #endif /* MS_WINDOWS */
571 strcpy(buf
, envpath
);
572 buf
= strchr(buf
, '\0');
577 strcpy(buf
, zip_path
);
578 buf
= strchr(buf
, '\0');
582 strcpy(buf
, userpath
);
583 buf
= strchr(buf
, '\0');
588 strcpy(buf
, machinepath
);
589 buf
= strchr(buf
, '\0');
593 if (pythonhome
== NULL
) {
595 strcpy(buf
, PYTHONPATH
);
596 buf
= strchr(buf
, '\0');
600 if (pythonhome
== NULL
) {
601 strcpy(buf
, PYTHONPATH
);
602 buf
= strchr(buf
, '\0');
604 #endif /* MS_WINDOWS */
606 char *p
= PYTHONPATH
;
610 q
= strchr(p
, DELIM
);
615 if (p
[0] == '.' && is_sep(p
[1])) {
616 strcpy(buf
, pythonhome
);
617 buf
= strchr(buf
, '\0');
631 strcpy(buf
, argv0_path
);
632 buf
= strchr(buf
, '\0');
635 /* Now to pull one last hack/trick. If sys.prefix is
636 empty, then try and find it somewhere on the paths
637 we calculated. We scan backwards, as our general policy
638 is that Python core directories are at the *end* of
639 sys.path. We assume that our "lib" directory is
640 on the path, and that our 'prefix' directory is
644 char lookBuf
[MAXPATHLEN
+1];
645 char *look
= buf
- 1; /* 'buf' is at the end of the buffer */
648 char *lookEnd
= look
;
649 /* 'look' will end up one character before the
650 start of the path in question - even if this
651 is one character before the start of the buffer
653 while (*look
!= DELIM
&& look
>= module_search_path
)
655 nchars
= lookEnd
-look
;
656 strncpy(lookBuf
, look
+1, nchars
);
657 lookBuf
[nchars
] = '\0';
658 /* Up one level to the parent */
660 if (search_for_prefix(lookBuf
, LANDMARK
)) {
663 /* If we are out of paths to search - give up */
664 if (look
< module_search_path
)
672 /* External interface */
677 if (!module_search_path
)
679 return module_search_path
;
685 if (!module_search_path
)
691 Py_GetExecPrefix(void)
693 return Py_GetPrefix();
697 Py_GetProgramFullPath(void)
699 if (!module_search_path
)