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

Skip to content

Commit a0dd22e

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

3 files changed

Lines changed: 17 additions & 4 deletions

File tree

Lib/test/test_cmd_line.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -376,12 +376,24 @@ def test_del___main__(self):
376376
print("del sys.modules['__main__']", file=script)
377377
assert_python_ok(filename)
378378

379-
380379
def test_unknown_options(self):
381-
rc, out, err = assert_python_failure('-z', __cleanenv=True)
382-
self.assertIn(b'Unknown option', err)
380+
rc, out, err = assert_python_failure('-E', '-z')
381+
self.assertIn(b'Unknown option: -z', err)
382+
self.assertEqual(err.splitlines().count(b'Unknown option: -z'), 1)
383+
self.assertEqual(b'', out)
384+
# Add "without='-E'" to prevent _assert_python to append -E
385+
# to env_vars and change the output of stderr
386+
rc, out, err = assert_python_failure('-z', without='-E')
387+
self.assertIn(b'Unknown option: -z', err)
383388
self.assertEqual(err.splitlines().count(b'Unknown option: -z'), 1)
384389
self.assertEqual(b'', out)
390+
rc, out, err = assert_python_failure('-a', '-z', without='-E')
391+
self.assertIn(b'Unknown option: -a', err)
392+
# only the first unknown option is reported
393+
self.assertNotIn(b'Unknown option: -z', err)
394+
self.assertEqual(err.splitlines().count(b'Unknown option: -a'), 1)
395+
self.assertEqual(b'', out)
396+
385397

386398
def test_main():
387399
test.support.run_unittest(CmdLineTest)

Modules/main.c

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

340340
/* Hash randomization needed early for all string operations
341341
(including -W and -X options). */
342+
_PyOS_opterr = 0; /* prevent printing the error in 1st pass */
342343
while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
343344
if (c == 'm' || c == 'c') {
344345
/* -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
@@ -45,7 +45,7 @@ static wchar_t *opt_ptr = L"";
4545

4646
void _PyOS_ResetGetOpt(void)
4747
{
48-
_PyOS_opterr = 0; /* prevent printing the error in 2nd loop in main.c */
48+
_PyOS_opterr = 1;
4949
_PyOS_optind = 1;
5050
_PyOS_optarg = NULL;
5151
opt_ptr = L"";

0 commit comments

Comments
 (0)