> Effettivamente così funziona l'esempio, purtroppo nel caso reale mi solleva > altri problemi (che sembrano completamente scorrelati), per cui quando avevo > fatto la prova, vedendo l'errore avevo.... cortocircuitato il cervello. Fra > poco indago meglio cosa mi sta dicendo l'errore.
trovato. Faccio un passo indietro. Sto aggiungendo la possibilità di scrivere un testo descrittivo alla ricetta di Simionato 'optionparse' [1]. In quella ricetta, le opzioni da passare al parser sono nella docstring, che viene 'parsata' con una regexp. Se la docstring è unicode anche i 'pezzetti' passati a parse.add_options, saranno unicode (alla riga 65): p.add_option(short.strip(),long.strip(), action = action, help = help.strip()) e questo non viene digerito da optparse. Quindi avevo pensato di fare diventare unicode solo le help string e la description, ma in effetti posso semplicemente fare ridiventare 'ascii' le opzioni... vedo che vanno ugualmente bene str() ed .encode('ascii'). sandro *:-) [1] http://code.activestate.com/recipes/278844/ ps: allego la versione finale... -- Sandro Dentella *:-) http://sqlkit.argolinux.org SQLkit home page - PyGTK/python/sqlalchemy
# coding: utf-8 """\ :Author: M. Simionato :Date: April 2004 :Title: A much simplified interface to optparse. You should use optionparse in your scripts as follows. First, write a module level docstring containing something like this (this is just an example): '''usage: %prog files [options] -d, --delete: delete all files -e, --erase = ERASE: erase the given file''' Then write a main program of this kind: # sketch of a script to delete files if __name__=='__main__': import optionparse option,args=optionparse.parse(__doc__) if not args and not option: optionparse.exit() elif option.delete: print "Delete all files" elif option.erase: print "Delete the given file" Notice that ``optionparse`` parses the docstring by looking at the characters ",", ":", "=", "\\n", so be careful in using them. If the docstring is not correctly formatted you will get a SyntaxError or worse, the script will not work as expected. """ import optparse, re, sys USAGE = re.compile(r'\s*(?P<descr>.*)\s*\s*usage: (?P<usage>.*?)(\n[ \t]*\n|$)', re.DOTALL|re.UNICODE|re.LOCALE) def nonzero(self): # will become the nonzero method of optparse.Values "True if options were given" for v in self.__dict__.itervalues(): if v is not None: return True return False optparse.Values.__nonzero__ = nonzero # dynamically fix optparse.Values class ParsingError(Exception): pass optionstring="" def exit(msg=""): raise SystemExit(msg or optionstring.replace("%prog",sys.argv[0])) def parse(docstring, arglist=None): global optionstring optionstring = docstring match = USAGE.search(optionstring) if not match: raise ParsingError("Cannot find the option string") optlines = match.group('usage').splitlines() try: descr = match.group('descr') p = optparse.OptionParser(optlines[0], description=descr) for line in optlines[1:]: opt, help=line.split(':')[:2] short,long=opt.split(',')[:2] if '=' in opt: action='store' long=long.split('=')[0] else: action='store_true' p.add_option(str(short.strip()),str(long.strip()), action = action, help = help.strip()) except (IndexError,ValueError): raise ParsingError("Cannot parse the option string correctly") return p.parse_args(arglist)
_______________________________________________ Python mailing list Python@lists.python.it http://lists.python.it/mailman/listinfo/python