Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7126dbc

Browse files
author
Victor Stinner
committed
Issue #3798: sys.exit(message) writes the message to sys.stderr file, instead
of the C file stderr, to use stderr encoding and error handler
1 parent 3df439d commit 7126dbc

3 files changed

Lines changed: 19 additions & 6 deletions

File tree

Lib/test/test_sys.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -146,9 +146,9 @@ def test_exit(self):
146146
"raise SystemExit(47)"])
147147
self.assertEqual(rc, 47)
148148

149-
def check_exit_message(code, expected):
149+
def check_exit_message(code, expected, env=None):
150150
process = subprocess.Popen([sys.executable, "-c", code],
151-
stderr=subprocess.PIPE)
151+
stderr=subprocess.PIPE, env=env)
152152
stdout, stderr = process.communicate()
153153
self.assertEqual(process.returncode, 1)
154154
self.assertTrue(stderr.startswith(expected),
@@ -166,6 +166,14 @@ def check_exit_message(code, expected):
166166
r'import sys; sys.exit("surrogates:\uDCFF")',
167167
b"surrogates:\\udcff")
168168

169+
# test that the unicode message is encoded to the stderr encoding
170+
# instead of the default encoding (utf8)
171+
env = os.environ.copy()
172+
env['PYTHONIOENCODING'] = 'latin-1'
173+
check_exit_message(
174+
r'import sys; sys.exit("h\xe9")',
175+
b"h\xe9", env=env)
176+
169177
def test_getdefaultencoding(self):
170178
self.assertRaises(TypeError, sys.getdefaultencoding, 42)
171179
# can't check more than the type, as the user might have changed it

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,9 @@ C-API
393393
Library
394394
-------
395395

396+
- Issue #3798: sys.exit(message) writes the message to sys.stderr file, instead
397+
of the C file stderr, to use stderr encoding and error handler
398+
396399
- Issue #8782: Add a trailing newline in linecache.updatecache to the last line
397400
of files without one.
398401

Python/pythonrun.c

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1386,10 +1386,12 @@ handle_system_exit(void)
13861386
exitcode = (int)PyLong_AsLong(value);
13871387
else {
13881388
PyObject *sys_stderr = PySys_GetObject("stderr");
1389-
if (sys_stderr != NULL)
1390-
PyObject_CallMethod(sys_stderr, "flush", NULL);
1391-
PyObject_Print(value, stderr, Py_PRINT_RAW);
1392-
fflush(stderr);
1389+
if (sys_stderr != NULL && sys_stderr != Py_None) {
1390+
PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1391+
} else {
1392+
PyObject_Print(value, stderr, Py_PRINT_RAW);
1393+
fflush(stderr);
1394+
}
13931395
PySys_WriteStderr("\n");
13941396
exitcode = 1;
13951397
}

0 commit comments

Comments
 (0)