2016-02-11 58 views
0

我想將'usage:'翻譯爲'foobar'。Python 3 gettext不適用於argparse

print(gettext.find('test', 'i18n', ['en_US'])) 
    translator = gettext.translation('test', localedir='i18n', languages=['en_US']) 
    translator.install() 
    print(_('usage: ')) 
    parser = argparse.ArgumentParser(prog="jcheq.py", 
            usage="%(prog)s [opciones] [paths...]\nThe paths are optional; if not given . is " 
              "used.", 
            add_help=False, 
            formatter_class=argparse.ArgumentDefaultsHelpFormatter) 

但它輸出這樣的:

~/Desktop/Proyectos/UNPAZ/jcheq/jcheq$ python3 jcheq.py --help 
i18n/en_US/LC_MESSAGES/test.mo 
foobar: 
usage: jcheq.py [opciones] [paths...] 
The paths are optional; if not given . is used. 

Opciones: 
    -h, --help  Mostrar este mensaje de ayuda y salir. 
    -m, --modified show last modified date/time (default: False) 

看來,它正在爲我的字符串,而不是argparse的一個:

argparse.py:292 aprox的

def _format_usage(self, usage, actions, groups, prefix): 
     if prefix is None: 
      prefix = _('usage: ') 
+0

在可能的幫助http://stackoverflow.com/questions/22951442/how-to-make-pythons-argparse-generate-non-english-text – hpaulj

回答

0

借用How to make python's argparse generate Non-English text?

import gettext 

def Übersetzung(Text): 
    Text = Text.replace("usage", "Verwendung") 
    Text = Text.replace("show this help message and exit", 
         "zeige diese Hilfe an und tue nichts weiteres") 
    Text = Text.replace("error:", "Fehler:") 
    Text = Text.replace("the following arguments are required:", 
         "Die folgenden Argumente müssen angegeben werden:") 
    return Text 
gettext.gettext = Übersetzung 

import argparse  
parser = argparse.ArgumentParser(prog="jcheq.py", 
      usage="%(prog)s [opciones] [paths...]\nThe paths are optional; if not given . is " 
        "used.") 
parser.print_usage() 
print() 
parser.print_help() 

生產:

1702:~/mypy$ python3 stack35347168.py 
Verwendung: jcheq.py [opciones] [paths...] 
The paths are optional; if not given . is used. 

Verwendung: jcheq.py [opciones] [paths...] 
The paths are optional; if not given . is used. 

optional arguments: 
    -h, --help zeige diese Hilfe an und tue nichts weiteres