Skip to content

Commit 8384670

Browse files
authored
bpo-20844: open script file with "rb" mode (GH-12616)
(cherry picked from commit 10654c1)
1 parent a37f356 commit 8384670

4 files changed

Lines changed: 24 additions & 1 deletion

File tree

Doc/c-api/veryhigh.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,10 @@ the same library that the Python runtime is using.
109109
(:func:`sys.getfilesystemencoding`). If *closeit* is true, the file is
110110
closed before PyRun_SimpleFileExFlags returns.
111111
112+
.. note::
113+
On Windows, *fp* should be opened as binary mode (e.g. ``fopen(filename, "rb")``.
114+
Otherwise, Python may not handle script file with LF line ending correctly.
115+
112116
113117
.. c:function:: int PyRun_InteractiveOne(FILE *fp, const char *filename)
114118

Lib/test/test_cmd_line_script.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,23 @@ def test_issue8202_dash_m_file_ignored(self):
387387
script_name, script_name, script_dir, '',
388388
importlib.machinery.SourceFileLoader)
389389

390+
def test_issue20884(self):
391+
# On Windows, script with encoding cookie and LF line ending
392+
# will be failed.
393+
with support.temp_dir() as script_dir:
394+
script_name = os.path.join(script_dir, "issue20884.py")
395+
with open(script_name, "w", newline='\n') as f:
396+
f.write("#coding: iso-8859-1\n")
397+
f.write('"""\n')
398+
for _ in range(30):
399+
f.write('x'*80 + '\n')
400+
f.write('"""\n')
401+
402+
with support.change_cwd(path=script_dir):
403+
rc, out, err = assert_python_ok(script_name)
404+
self.assertEqual(b"", out)
405+
self.assertEqual(b"", err)
406+
390407
@contextlib.contextmanager
391408
def setup_test_pkg(self, *args):
392409
with support.temp_dir() as script_dir, \
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix running script with encoding cookie and LF line ending
2+
may fail on Windows.

Modules/main.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1534,7 +1534,7 @@ pymain_open_filename(_PyMain *pymain)
15341534
const _PyCoreConfig *config = &_PyGILState_GetInterpreterStateUnsafe()->core_config;
15351535
FILE* fp;
15361536

1537-
fp = _Py_wfopen(pymain->filename, L"r");
1537+
fp = _Py_wfopen(pymain->filename, L"rb");
15381538
if (fp == NULL) {
15391539
char *cfilename_buffer;
15401540
const char *cfilename;

0 commit comments

Comments
 (0)