如何在 Python 中更改 Windows 代码页?

发布于 2024-09-16 00:12:50 字数 520 浏览 1 评论 0原文

考虑一下:

>>> a = os.popen('chcp 65001')
>>> a.read()
'Active code page: 65001\n'
>>> a.close()
>>> a = os.popen('chcp')
>>> a.read()
'Active code page: 437\n'
>>> a.close()

在我将代码页设置为 65001 后,下次调用 CHCP 它应该说活动代码页是 65001,而不是 437。我在 Windows 命令提示符中尝试过此操作它起作用了。

为什么它不能通过 Python 代码运行?

Consider:

>>> a = os.popen('chcp 65001')
>>> a.read()
'Active code page: 65001\n'
>>> a.close()
>>> a = os.popen('chcp')
>>> a.read()
'Active code page: 437\n'
>>> a.close()

After I set the code page to 65001, the next time I call CHCP it should say the active code page is 65001, not 437. I tried this in the Windows command prompt and it worked.

Why doesn't it work through Python code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

铁轨上的流浪者 2024-09-23 00:12:50

原因是每次调用 os.popen 时都会生成一个新进程。尝试打开两个 cmd.exe 会话,并在一个会话中运行 chcp 65001,在另一个会话中运行 chcp — 这就是您在 Python 中所做的事情代码。

需要注意的一件事:所有 popen*() 调用从 Python 2.6 开始已被弃用。要使用的新模块是 subprocess 模块。

The reason is that every time you call os.popen you are spawning a new process. Try opening up two cmd.exe sessions and running chcp 65001 in one and chcp in the other—that's what you are doing here in your Python code.

One thing to note: all of the popen*() calls are deprecated as of Python 2.6. The new module to use is the subprocess module.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文