Skip to content

Commit ed51b26

Browse files
committed
Issue python#28137: Renames Windows path file to ._pth
Issue python#28138: Windows ._pth file should allow import site
1 parent 313523c commit ed51b26

5 files changed

Lines changed: 119 additions & 52 deletions

File tree

Doc/using/windows.rst

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -720,15 +720,24 @@ installation directory. So, if you had installed Python to
720720
:file:`C:\\Python\\Lib\\` and third-party modules should be stored in
721721
:file:`C:\\Python\\Lib\\site-packages\\`.
722722

723-
To completely override :data:`sys.path`, create a text file named ``'sys.path'``
724-
containing a list of paths alongside the Python executable. This will ignore all
725-
registry settings and environment variables, enable isolated mode, disable
726-
importing :mod:`site`, and fill :data:`sys.path` with exactly the paths listed
727-
in the file. Paths may be absolute or relative to the directory containing the
728-
file.
723+
To completely override :data:`sys.path`, create a ``._pth`` file with the same
724+
name as the DLL (``python36._pth``) or the executable (``python._pth``) and
725+
specify one line for each path to add to :data:`sys.path`. The file based on the
726+
DLL name overrides the one based on the executable, which allows paths to be
727+
restricted for any program loading the runtime if desired.
729728

730-
When the ``'sys.path'`` file is missing, this is how :data:`sys.path` is
731-
populated on Windows:
729+
When the file exists, all registry and environment variables are ignored,
730+
isolated mode is enabled, and :mod:`site` is not imported unless one line in the
731+
file specifies ``import site``. Blank paths and lines starting with ``#`` are
732+
ignored. Each path may be absolute or relative to the location of the file.
733+
Import statements other than to ``site`` are not permitted, and arbitrary code
734+
cannot be specified.
735+
736+
Note that ``.pth`` files (without leading underscore) will be processed normally
737+
by the :mod:`site` module.
738+
739+
When no ``._pth`` file is found, this is how :data:`sys.path` is populated on
740+
Windows:
732741

733742
* An empty entry is added at the start, which corresponds to the current
734743
directory.
@@ -782,9 +791,10 @@ The end result of all this is:
782791
For those who want to bundle Python into their application or distribution, the
783792
following advice will prevent conflicts with other installations:
784793

785-
* Include a ``sys.path`` file alongside your executable containing the
786-
directories to include. This will ignore user site-packages and other paths
787-
listed in the registry or in environment variables.
794+
* Include a ``._pth`` file alongside your executable containing the
795+
directories to include. This will ignore paths listed in the registry and
796+
environment variables, and also ignore :mod:`site` unless ``import site`` is
797+
listed.
788798

789799
* If you are loading :file:`python3.dll` or :file:`python36.dll` in your own
790800
executable, explicitly call :c:func:`Py_SetPath` or (at least)

Doc/whatsnew/3.6.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ Windows improvements:
108108
which means that when the 260 character path limit may no longer apply.
109109
See :ref:`removing the MAX_PATH limitation <max-path>` for details.
110110

111-
* A ``sys.path`` file can be added to force isolated mode and fully specify
111+
* A ``._pth`` file can be added to force isolated mode and fully specify
112112
all search paths to avoid registry and environment lookup. See
113113
:ref:`the documentation <finding_modules>` for more information.
114114

Misc/NEWS

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ What's New in Python 3.6.0 beta 2
1010
Core and Builtins
1111
-----------------
1212

13+
- Issue #28192: Don't import readline in isolated mode.
14+
1315
- Upgrade internal unicode databases to Unicode version 9.0.0.
1416

1517
- Issue #28131: Fix a regression in zipimport's compile_source(). zipimport
@@ -64,6 +66,13 @@ Library
6466
- Issue #27759: Fix selectors incorrectly retain invalid file descriptors.
6567
Patch by Mark Williams.
6668

69+
Windows
70+
-------
71+
72+
- Issue #28137: Renames Windows path file to ._pth
73+
74+
- Issue #28138: Windows ._pth file should allow import site
75+
6776
Build
6877
-----
6978

PC/getpathp.c

Lines changed: 78 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@
66
PATH RULES FOR WINDOWS:
77
This describes how sys.path is formed on Windows. It describes the
88
functionality, not the implementation (ie, the order in which these
9-
are actually fetched is different). The presence of a sys.path file
10-
alongside the program overrides these rules - see below.
9+
are actually fetched is different). The presence of a python._pth or
10+
pythonXY._pth file alongside the program overrides these rules - see
11+
below.
1112
1213
* Python always adds an empty entry at the start, which corresponds
1314
to the current directory.
@@ -37,11 +38,21 @@
3738
used (eg. .\Lib;.\DLLs, etc)
3839
3940
40-
If a sys.path file exists adjacent to python.exe, it must contain a
41-
list of paths to add to sys.path, one per line (like a .pth file but without
42-
the ability to execute arbitrary code). Each path is relative to the
43-
directory containing the file. No other paths are added to the search path,
44-
and the registry finder is not enabled.
41+
If a '._pth' file exists adjacent to the executable with the same base name
42+
(e.g. python._pth adjacent to python.exe) or adjacent to the shared library
43+
(e.g. python36._pth adjacent to python36.dll), it is used in preference to
44+
the above process. The shared library file takes precedence over the
45+
executable. The path file must contain a list of paths to add to sys.path,
46+
one per line. Each path is relative to the directory containing the file.
47+
Blank lines and comments beginning with '#' are permitted.
48+
49+
In the presence of this ._pth file, no other paths are added to the search
50+
path, the registry finder is not enabled, site.py is not imported and
51+
isolated mode is enabled. The site package can be enabled by including a
52+
line reading "import site"; no other imports are recognized. Any invalid
53+
entry (other than directories that do not exist) will result in immediate
54+
termination of the program.
55+
4556
4657
The end result of all this is:
4758
* When running python.exe, or any other .exe in the main Python directory
@@ -61,8 +72,9 @@
6172
* An embedding application can use Py_SetPath() to override all of
6273
these automatic path computations.
6374
64-
* An isolation install of Python can disable all implicit paths by
65-
providing a sys.path file.
75+
* An install of Python can fully specify the contents of sys.path using
76+
either a 'EXENAME._pth' or 'DLLNAME._pth' file, optionally including
77+
"import site" to enable the site module.
6678
6779
---------------------------------------------------------------- */
6880

@@ -135,6 +147,33 @@ reduce(wchar_t *dir)
135147
dir[i] = '\0';
136148
}
137149

150+
static int
151+
change_ext(wchar_t *dest, const wchar_t *src, const wchar_t *ext)
152+
{
153+
size_t src_len = wcsnlen_s(src, MAXPATHLEN+1);
154+
size_t i = src_len;
155+
if (i >= MAXPATHLEN+1)
156+
Py_FatalError("buffer overflow in getpathp.c's reduce()");
157+
158+
while (i > 0 && src[i] != '.' && !is_sep(src[i]))
159+
--i;
160+
161+
if (i == 0) {
162+
dest[0] = '\0';
163+
return -1;
164+
}
165+
166+
if (is_sep(src[i]))
167+
i = src_len;
168+
169+
if (wcsncpy_s(dest, MAXPATHLEN+1, src, i) ||
170+
wcscat_s(dest, MAXPATHLEN+1, ext)) {
171+
dest[0] = '\0';
172+
return -1;
173+
}
174+
175+
return 0;
176+
}
138177

139178
static int
140179
exists(wchar_t *filename)
@@ -499,12 +538,17 @@ find_env_config_value(FILE * env_file, const wchar_t * key, wchar_t * value)
499538
}
500539

501540
static int
502-
read_sys_path_file(const wchar_t *path, const wchar_t *prefix)
541+
read_pth_file(const wchar_t *path, wchar_t *prefix, int *isolated, int *nosite)
503542
{
504543
FILE *sp_file = _Py_wfopen(path, L"r");
505544
if (sp_file == NULL)
506545
return -1;
507546

547+
wcscpy_s(prefix, MAXPATHLEN+1, path);
548+
reduce(prefix);
549+
*isolated = 1;
550+
*nosite = 1;
551+
508552
size_t bufsiz = MAXPATHLEN;
509553
size_t prefixlen = wcslen(prefix);
510554

@@ -516,16 +560,25 @@ read_sys_path_file(const wchar_t *path, const wchar_t *prefix)
516560
char *p = fgets(line, MAXPATHLEN + 1, sp_file);
517561
if (!p)
518562
break;
563+
if (*p == '\0' || *p == '#')
564+
continue;
565+
while (*++p) {
566+
if (*p == '\r' || *p == '\n') {
567+
*p = '\0';
568+
break;
569+
}
570+
}
519571

520-
DWORD n = strlen(line);
521-
if (n == 0 || p[n - 1] != '\n')
522-
break;
523-
if (n > 2 && p[n - 1] == '\r')
524-
--n;
572+
if (strcmp(line, "import site") == 0) {
573+
*nosite = 0;
574+
continue;
575+
} else if (strncmp(line, "import ", 7) == 0) {
576+
Py_FatalError("only 'import site' is supported in ._pth file");
577+
}
525578

526-
DWORD wn = MultiByteToWideChar(CP_UTF8, 0, line, n - 1, NULL, 0);
579+
DWORD wn = MultiByteToWideChar(CP_UTF8, 0, line, -1, NULL, 0);
527580
wchar_t *wline = (wchar_t*)PyMem_RawMalloc((wn + 1) * sizeof(wchar_t));
528-
wn = MultiByteToWideChar(CP_UTF8, 0, line, n - 1, wline, wn);
581+
wn = MultiByteToWideChar(CP_UTF8, 0, line, -1, wline, wn + 1);
529582
wline[wn] = '\0';
530583

531584
while (wn + prefixlen + 4 > bufsiz) {
@@ -539,8 +592,8 @@ read_sys_path_file(const wchar_t *path, const wchar_t *prefix)
539592

540593
if (buf[0])
541594
wcscat_s(buf, bufsiz, L";");
595+
542596
wchar_t *b = &buf[wcslen(buf)];
543-
544597
wcscat_s(buf, bufsiz, prefix);
545598
join(b, wline);
546599

@@ -586,13 +639,12 @@ calculate_path(void)
586639
{
587640
wchar_t spbuffer[MAXPATHLEN+1];
588641

589-
wcscpy_s(spbuffer, MAXPATHLEN+1, argv0_path);
590-
join(spbuffer, L"sys.path");
591-
if (exists(spbuffer) && read_sys_path_file(spbuffer, argv0_path) == 0) {
592-
wcscpy_s(prefix, MAXPATHLEN + 1, argv0_path);
593-
Py_IsolatedFlag = 1;
594-
Py_NoSiteFlag = 1;
595-
return;
642+
if ((dllpath[0] && !change_ext(spbuffer, dllpath, L"._pth") && exists(spbuffer)) ||
643+
(progpath[0] && !change_ext(spbuffer, progpath, L"._pth") && exists(spbuffer))) {
644+
645+
if (!read_pth_file(spbuffer, prefix, &Py_IsolatedFlag, &Py_NoSiteFlag)) {
646+
return;
647+
}
596648
}
597649
}
598650

@@ -631,16 +683,7 @@ calculate_path(void)
631683
}
632684

633685
/* Calculate zip archive path from DLL or exe path */
634-
if (wcscpy_s(zip_path, MAXPATHLEN + 1, dllpath[0] ? dllpath : progpath)) {
635-
/* exceeded buffer length - ignore zip_path */
636-
zip_path[0] = '\0';
637-
} else {
638-
wchar_t *dot = wcsrchr(zip_path, '.');
639-
if (!dot || wcscpy_s(dot, MAXPATHLEN + 1 - (dot - zip_path), L".zip")) {
640-
/* exceeded buffer length - ignore zip_path */
641-
zip_path[0] = L'\0';
642-
}
643-
}
686+
change_ext(zip_path, dllpath[0] ? dllpath : progpath, L".zip");
644687

645688
if (pythonhome == NULL || *pythonhome == '\0') {
646689
if (zip_path[0] && exists(zip_path)) {

Tools/msi/make_zip.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -91,11 +91,13 @@ def include_in_tools(p):
9191

9292
return p.suffix.lower() in {'.py', '.pyw', '.txt'}
9393

94+
BASE_NAME = 'python{0.major}{0.minor}'.format(sys.version_info)
95+
9496
FULL_LAYOUT = [
9597
('/', 'PCBuild/$arch', 'python.exe', is_not_debug),
9698
('/', 'PCBuild/$arch', 'pythonw.exe', is_not_debug),
97-
('/', 'PCBuild/$arch', 'python{0.major}.dll'.format(sys.version_info), is_not_debug),
98-
('/', 'PCBuild/$arch', 'python{0.major}{0.minor}.dll'.format(sys.version_info), is_not_debug),
99+
('/', 'PCBuild/$arch', 'python{}.dll'.format(sys.version_info.major), is_not_debug),
100+
('/', 'PCBuild/$arch', '{}.dll'.format(BASE_NAME), is_not_debug),
99101
('DLLs/', 'PCBuild/$arch', '*.pyd', is_not_debug),
100102
('DLLs/', 'PCBuild/$arch', '*.dll', is_not_debug_or_python),
101103
('include/', 'include', '*.h', None),
@@ -109,7 +111,7 @@ def include_in_tools(p):
109111
('/', 'PCBuild/$arch', 'python*.exe', is_not_debug),
110112
('/', 'PCBuild/$arch', '*.pyd', is_not_debug),
111113
('/', 'PCBuild/$arch', '*.dll', is_not_debug),
112-
('python{0.major}{0.minor}.zip'.format(sys.version_info), 'Lib', '**/*', include_in_lib),
114+
('{}.zip'.format(BASE_NAME), 'Lib', '**/*', include_in_lib),
113115
]
114116

115117
if os.getenv('DOC_FILENAME'):
@@ -209,9 +211,12 @@ def main():
209211
print('Copied {} files'.format(copied))
210212

211213
if ns.embed:
212-
with open(str(temp / 'sys.path'), 'w') as f:
213-
print('python{0.major}{0.minor}.zip'.format(sys.version_info), file=f)
214+
with open(str(temp / (BASE_NAME + '._pth')), 'w') as f:
215+
print(BASE_NAME + '.zip', file=f)
214216
print('.', file=f)
217+
print('', file=f)
218+
print('# Uncomment to run site.main() automatically', file=f)
219+
print('#import site', file=f)
215220

216221
if out:
217222
total = copy_to_layout(out, rglob(temp, '**/*', None))

0 commit comments

Comments
 (0)