pyperclip更改语言环境

时间:2019-01-24 23:40:25

标签: python

我有一个简单的脚本来生成一些带有日期的文本。它是一个基于命令的实用程序,具有简单的循环读取命令的功能。最终,一个输入w将结果写入文件。

由于我需要与日历相关的名称(天,月,...)的特定语言环境,因此我使用:

locale.setlocale(locale.LC_ALL, 'nb_NO.utf8')

这很好。但是,然后我添加了新功能,可以将结果复制到剪贴板。问题是pyperclip似乎会更改/重置语言环境。

从脚本中提取的简单示例代码:

#!/usr/bin/env python3

import sys
import datetime, calendar, locale
from contextlib import redirect_stdout
from io import StringIO
import pyperclip


locale.setlocale(locale.LC_ALL, 'nb_NO.utf8')

today = datetime.date(2019, 10, 1)

class Shedule():
    def datem(self, dd):
        return dd.strftime("%-d. %b")

    def print(self, heading):
        # locale.setlocale(locale.LC_ALL, 'nb_NO.utf8')
        print("%s: %s" % (heading, self.datem(today)))


    def copy(self, heading):
        buf = StringIO()
        with redirect_stdout(buf):
            shed.print(heading)
        print("%s" % buf.getvalue(), end="")
        pyperclip.copy(buf.getvalue())

shed = Shedule()

shed.print("Test 1")

shed.copy("Test 2")

print("After pyper")

shed.print("Test 3")

shed.copy("Test 4")

shed.print("Test 5")

结果(此处):

Test 1: 1. okt.
Test 2: 1. okt.
After pyper
Test 3: 1. Oct
Test 4: 1. Oct
Test 5: 1. Oct

如您所见,在pyper之后,调用shed.print()会得到Oct而不是区域设置okt.


如何最好地解决这个问题?

如果我取消注释Shedule.print()方法的第一行,它会起作用,但是还有更好的方法吗?为什么会首先发生?


简单的示例代码:

#!/usr/bin/env python3

import datetime, locale, pyperclip

locale.setlocale(locale.LC_ALL, 'nb_NO.utf8')

sample_date = datetime.date(2019, 10, 1)

print("Test 1: %s" % sample_date.strftime('%b'))
pyperclip.copy('')
print("Test 2: %s" % sample_date.strftime('%b'))

结果:

Test 1: okt.
Test 2: Oct

0 个答案:

没有答案