[Python-Dev] optparse and unicode

Tom Cato Amundsen tca at gnu.org
Tue May 30 22:32:11 CEST 2006


optparse
========
Using unicode strings with non-ascii chars.[1]
I'm working around this by subclassing OptionParser. Below is a
workaround I use in GNU Solfege. Should something like this be
included in python 2.5?
(Please CC me any answer.)
Tom Cato
--- orig/src/mainwin.py
+++ mod/src/mainwin.py
@@ -30,7 +30,13 @@
 
 import optparse
 
-opt_parser = optparse.OptionParser()
+class MyOptionParser(optparse.OptionParser):
+ def print_help(self, file=None):
+ if file is None:
+ file = sys.stdout
+ file.write(self.format_help().encode(file.encoding, 'replace'))
+
+opt_parser = MyOptionParser()
 opt_parser.add_option('-v', '--version', action='store_true', dest='version')
 opt_parser.add_option('-w', '--warranty', action='store_true', dest='warranty',
 help=_('Show warranty and copyright.'))
[1]
Traceback (most recent call last):
 File "./solfege.py", line 43, in ?
 import src.mainwin
 File "/home/tom/src/solfege-mcnv/src/mainwin.py", line 70, in ?
 options, args = opt_parser.parse_args()
 File "/usr/lib/python2.3/optparse.py", line 1129, in parse_args
 stop = self._process_args(largs, rargs, values)
 File "/usr/lib/python2.3/optparse.py", line 1169, in _process_args
 self._process_long_opt(rargs, values)
 File "/usr/lib/python2.3/optparse.py", line 1244, in _process_long_opt
 option.process(opt, value, values, self)
 File "/usr/lib/python2.3/optparse.py", line 611, in process
 return self.take_action(
 File "/usr/lib/python2.3/optparse.py", line 632, in take_action
 parser.print_help()
 File "/usr/lib/python2.3/optparse.py", line 1370, in print_help
 file.write(self.format_help())
UnicodeEncodeError: 'ascii' codec can't encode characters in position 200-202: ordinal not in range(128)
-- 
Tom Cato Amundsen <tca at gnu.org> http://www.solfege.org/
GNU Solfege - free ear training http://www.gnu.org/software/solfege/


More information about the Python-Dev mailing list

AltStyle によって変換されたページ (->オリジナル) /