在 Python 中更改区域设置后如何将其重置回原始设置?

How to reset locale back to original after changing it in Python?

在 Python 程序中更改区域设置后,将其更改回原始值的安全方法是什么?

到目前为止我尝试的是存储 locale.getlocale 返回的原始语言环境 在进行更改之前,然后使用 locale.setlocale 更改回它。

示例程序:

import datetime
import locale

now = datetime.datetime.now()

locale.setlocale(locale.LC_ALL, '')
print("Date using your locale      : %s" % now.strftime('%c'))

saved = locale.getlocale(locale.LC_TIME)
locale.setlocale(locale.LC_TIME, 'C')
print("Date using the C locale     : %s" % now.strftime('%c'))

locale.setlocale(locale.LC_TIME, saved)
print("Date using your locale again: %s" % now.strftime('%c'))

但是,这并不总是按预期工作。问题似乎出现在具有 修饰符 ('@' 符号之后的位)的语言环境中。在 Debian 10 系统上使用 Python 3.7 尝试以下说明问题:

$ LC_TIME=sr_RS.utf8@latin python3 example.py
Date using your locale      : četvrtak, 01. avgust 2019. 14:43:43 
Date using the C locale     : Thu Aug  1 14:43:43 2019
Date using your locale again: четвртак, 01. август 2019. 14:43:43

所以它似乎改回 sr_RS.utf8 语言环境而不是原来的 sr_RS.utf8@latin 语言环境,忘记了 @latin 修饰符。

此外,如果不带修饰符的相应语言环境不可用,则尝试切换回来时会出错。例如,在 nan_TW.utf8@latin 语言环境存在但 nan_TW.utf8 不存在的系统上:

$ LC_TIME=nan_TW.utf8@latin python3 example.py
Date using your locale      : 2019 8g 01 (p4) 14:44:29 
Date using the C locale     : Thu Aug  1 14:44:29 2019
Traceback (most recent call last):
  File "example.py", line 13, in <module>
    locale.setlocale(locale.LC_TIME, saved)
  File "/usr/local/lib/python3.7/locale.py", line 604, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting

有没有安全的方法可以切换回原来的区域设置?例如,可以在库例程中使用的东西,旨在用于更大的区域设置感知程序中,以临时切换区域设置(例如,用于在另一个区域设置中格式化日期)然后将其切换回来,而不会永久干扰区域设置调用程序。

Is there a safe way to switch back to the original locale setting? (if it uses modifiers as e.g. latin)

不,不是标准函数调用:locale.getlocale() 忽略除 euro 之外的所有修饰符,请参阅 source

解决方法是使用内部函数 _setlocale,即不带 _parse_localename 部分的逆向工程 getlocale

import datetime
import locale

now = datetime.datetime.now()

locale.setlocale(locale.LC_ALL, '')
print("Date using your locale      : %s" % now.strftime('%c'))

saved = locale._setlocale(locale.LC_TIME)

locale.setlocale(locale.LC_TIME, 'C')
print("Date using the C locale     : %s" % now.strftime('%c'))

locale.setlocale(locale.LC_TIME, saved)
print("Date using your locale again: %s" % now.strftime('%c'))

示例:

$ LC_TIME=sr_RS.utf8@latin python3 so57312038.py
Date using your locale      : sreda, 21. avgust 2019. 00:00:29 
Date using the C locale     : Wed Aug 21 00:00:29 2019
Date using your locale again: sreda, 21. avgust 2019. 00:00:29