Skip to content

Commit f624ff4

Browse files
committed
#16306: report only the first unknown option and add more tests. Patch by Serhiy Storchaka.
1 parent f49be95 commit f624ff4

3 files changed

Lines changed: 16 additions & 5 deletions

File tree

Lib/test/test_cmd_line.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -116,14 +116,24 @@ def test_del___main__(self):
116116
print >>script, "del sys.modules['__main__']"
117117
assert_python_ok(filename)
118118

119-
120119
def test_unknown_options(self):
121-
# Add "without='-E'" to prevent _assert_python append env_vars -E
122-
# which changes the output of stderr
120+
rc, out, err = assert_python_failure('-E', '-z')
121+
self.assertIn(b'Unknown option: -z', err)
122+
self.assertEqual(err.splitlines().count(b'Unknown option: -z'), 1)
123+
self.assertEqual(b'', out)
124+
# Add "without='-E'" to prevent _assert_python to append -E
125+
# to env_vars and change the output of stderr
123126
rc, out, err = assert_python_failure('-z', without='-E')
124-
self.assertIn(b'Unknown option', err)
127+
self.assertIn(b'Unknown option: -z', err)
125128
self.assertEqual(err.splitlines().count(b'Unknown option: -z'), 1)
126129
self.assertEqual(b'', out)
130+
rc, out, err = assert_python_failure('-a', '-z', without='-E')
131+
self.assertIn(b'Unknown option: -a', err)
132+
# only the first unknown option is reported
133+
self.assertNotIn(b'Unknown option: -z', err)
134+
self.assertEqual(err.splitlines().count(b'Unknown option: -a'), 1)
135+
self.assertEqual(b'', out)
136+
127137

128138
def test_main():
129139
test.test_support.run_unittest(CmdLineTest)

Modules/main.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,7 @@ Py_Main(int argc, char **argv)
264264

265265
/* Hash randomization needed early for all string operations
266266
(including -W and -X options). */
267+
_PyOS_opterr = 0; /* prevent printing the error in 1st pass */
267268
while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
268269
if (c == 'm' || c == 'c') {
269270
/* -c / -m is the last option: following arguments are

Python/getopt.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ static char *opt_ptr = "";
4141

4242
void _PyOS_ResetGetOpt(void)
4343
{
44-
_PyOS_opterr = 0; /* prevent printing the error in 2nd loop in main.c */
44+
_PyOS_opterr = 1;
4545
_PyOS_optind = 1;
4646
_PyOS_optarg = NULL;
4747
opt_ptr = "";

0 commit comments

Comments
 (0)