如何在Python中找到所有可用的语言环境

时间:2018-11-15 13:13:37

标签: python locale

如何(在GNU / Linux系统上)找到所有可用的语言环境与模块locale一起使用?

我发现模块中唯一与之接近的是字典locale_alias,带有区域设置的别名。 有时提到这是在哪里可以看到您所拥有的语言环境,但是它并不包含所有别名。在我的系统上,该程序

#! /usr/bin/python3
import locale
for k, v in sorted(locale.locale_alias.items()):
    if k.startswith('fr_') or v.startswith('fr_'):
        print('{:20}{}'.format(k, v))

打印

c-french            fr_CA.ISO8859-1
fr                  fr_FR.ISO8859-1
fr_be               fr_BE.ISO8859-1
fr_ca               fr_CA.ISO8859-1
fr_ch               fr_CH.ISO8859-1
fr_fr               fr_FR.ISO8859-1
fr_lu               fr_LU.ISO8859-1
français            fr_FR.ISO8859-1
fre_fr              fr_FR.ISO8859-1
french              fr_FR.ISO8859-1
french.iso88591     fr_CH.ISO8859-1
french_france       fr_FR.ISO8859-1

忽略所有utf-8语言环境,例如'fr_FR.utf8',这些语言环境实际上可以用作locale.setlocale的参数。 locale -a | grep "^fr_.*utf8"从外壳中给出

fr_BE.utf8
fr_CA.utf8
fr_CH.utf8
fr_FR.utf8
fr_LU.utf8

显示很多选项。 (当然,有一种方法可以从Python运行此Shell命令,但我认为有一种方法可以直接从Python执行此操作。)

1 个答案:

答案 0 :(得分:0)

似乎没有直接从Python直接执行此操作的好方法,因此我将回答如何从Python运行此shell命令。

#! /usr/bin/python3
import subprocess

def find_locales():
    out = subprocess.run(['locale', '-a'], stdout=subprocess.PIPE).stdout
    try:
        # Even though I use utf8 on my system output from "locale -a"
        # included "bokmål" in Latin-1. Then this won't work, but the
        # exception will.
        res = out.decode('utf-8')
    except:
        res = out.decode('latin-1')
    return res.rstrip('\n').splitlines()

if __name__ == "__main__":
    for loc in find_locales():
        print(loc)

请注意,subprocess.run是Python 3.5中的新增功能。对于早期的Python版本,see this question介绍了运行Shell命令的替代方法。

相关问题