Index: Lib/optparse.py =================================================================== --- Lib/optparse.py (revision 67183) +++ Lib/optparse.py (working copy) @@ -1146,6 +1146,9 @@ have defined custom types; see SF bug #955889.) Set it to false to restore the behaviour of Optik 1.4.1 and earlier. + error_log : file + if given, errors will be logged to this file instead of stderr + rargs : [string] the argument list currently being parsed. Only set when parse_args() is active, and continually trimmed down as @@ -1178,7 +1181,8 @@ formatter=None, add_help_option=True, prog=None, - epilog=None): + epilog=None, + error_log=None): OptionContainer.__init__( self, option_class, conflict_handler, description) self.set_usage(usage) @@ -1191,6 +1195,9 @@ self.formatter = formatter self.formatter.set_parser(self) self.epilog = epilog + if error_log is None: + error_log = sys.stderr + self.error_log = error_log # Populate the option list; initial sources are the # standard_option_list class attribute, the 'option_list' @@ -1353,7 +1360,7 @@ Parse the command-line options found in 'args' (default: sys.argv[1:]). Any errors result in a call to 'error()', which - by default prints the usage message to stderr and calls + by default prints the usage message to the error log and calls sys.exit() with an error message. On success returns a pair (values, args) where 'values' is an Values instance (with all your option values) and 'args' is the list of arguments left @@ -1550,17 +1557,17 @@ def exit(self, status=0, msg=None): if msg: - sys.stderr.write(msg) + self.error_log.write(msg) sys.exit(status) def error(self, msg): """error(msg : string) - Print a usage message incorporating 'msg' to stderr and exit. + Print a usage message incorporating 'msg' to error_log and exit. If you override this in a subclass, it should not return -- it should either exit or raise an exception. """ - self.print_usage(sys.stderr) + self.print_usage(self.error_log) self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg)) def get_usage(self): Index: Lib/test/test_optparse.py =================================================================== --- Lib/test/test_optparse.py (revision 67183) +++ Lib/test/test_optparse.py (working copy) @@ -1630,6 +1630,29 @@ "option -l: invalid long integer value: '0x12x'") +class TestErrorLog(BaseTest): + def setUp(self): + self.log = StringIO() + self.parser = OptionParser(error_log=self.log) + self.parser.add_option('-f') + + def test_no_output_when_successful(self): + self.parser.parse_args(['-f', 'foo']) + self.assertEqual('', self.log.getvalue()) + + def test_log_on_failure(self): + try: + self.parser.parse_args(['--fail']) + except SystemExit: + pass + expect = \ +"""Usage: test_optparse.py [options] + +test_optparse.py: error: no such option: --fail +""" + self.assertEqual(expect, self.log.getvalue()) + + def test_main(): test_support.run_unittest(__name__)