console-default-encoding 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ from .con_de import get_console_default_encoding
2
+
3
+ __all__ = [
4
+ "get_console_default_encoding"
5
+ ]
@@ -0,0 +1,94 @@
1
+ import locale
2
+ import sys
3
+ import platform
4
+ from typing import Optional
5
+ import os
6
+
7
+ try:
8
+ from .get_cp0 import get_cp0_value
9
+ except:
10
+ from get_cp0 import get_cp0_value
11
+
12
+ def get_console_default_encoding_raw() -> Optional[str]:
13
+ encoding = None
14
+ system = platform.system().lower()
15
+
16
+ try:
17
+ # ========== 1. Windows 系统(优先获取控制台代码页) ==========
18
+ if system == "windows":
19
+ try:
20
+ # 导入 Windows 专属模块,获取控制台代码页
21
+ import ctypes
22
+ from ctypes import wintypes
23
+
24
+ # 获取标准输出的代码页
25
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
26
+ handle = kernel32.GetStdHandle(-11) # STD_OUTPUT_HANDLE
27
+ codepage = wintypes.UINT()
28
+ success = kernel32.GetConsoleOutputCP(ctypes.byref(codepage))
29
+ if success:
30
+ # 代码页映射:936=gbk,65001=utf-8,437=IBM437 等
31
+ codepage_map = {
32
+ 936: "gbk",
33
+ 65001: "utf-8",
34
+ 437: "ibm437",
35
+ 1252: "cp1252",
36
+ 950: "big5"
37
+ }
38
+ encoding = codepage_map.get(codepage.value, f"cp{codepage.value}")
39
+ except (ImportError, OSError, AttributeError):
40
+ # 兜底:使用 locale 模块获取 Windows 默认编码
41
+ encoding = locale.getdefaultlocale()[1]
42
+
43
+ # ========== 2. Linux/macOS 系统 ==========
44
+ else:
45
+ # 方式1:通过 locale 获取终端编码
46
+ try:
47
+ encoding = locale.getpreferredencoding()
48
+ except (locale.Error, ValueError):
49
+ # 方式2:读取环境变量(LC_CTYPE/LANG)
50
+ env_vars = ["LC_CTYPE", "LANG"]
51
+ for var in env_vars:
52
+ if var in os.environ:
53
+ # 从环境变量中提取编码(如 LANG=zh_CN.UTF-8 → utf-8)
54
+ lang_str = os.environ[var]
55
+ if "." in lang_str:
56
+ encoding = lang_str.split(".")[-1].lower()
57
+ break
58
+
59
+ # ========== 3. 最终兜底:使用 Python 标准流编码 ==========
60
+ if not encoding:
61
+ # 优先用 stdout 编码,失败则用 stdin
62
+ encoding = sys.stdout.encoding or sys.stdin.encoding
63
+
64
+ # 统一转为小写,标准化名称(如 GBK → gbk,UTF-8 → utf-8)
65
+ if encoding:
66
+ encoding = encoding.lower().replace("-", "")
67
+ # 兼容别名:cp936 → gbk
68
+ if encoding == "cp936":
69
+ encoding = "gbk"
70
+ elif encoding == "cp65001":
71
+ encoding = "utf8"
72
+
73
+ return encoding
74
+
75
+ except Exception as e:
76
+ print(f"检测命令行编码时出错:{e}")
77
+ return None
78
+
79
+ def get_console_default_encoding() -> Optional[str]:
80
+ """
81
+ 获取当前系统命令行(控制台/终端)的默认编码格式(如 gbk、utf-8)
82
+
83
+ Returns:
84
+ Optional[str]: 成功返回编码名称(小写),失败返回 None
85
+ """
86
+
87
+ cpx = get_console_default_encoding_raw()
88
+ if cpx == "cp0" or (cpx is None):
89
+ return get_cp0_value()["encoding_name"]
90
+ else:
91
+ return cpx
92
+
93
+ if __name__ == "__main__":
94
+ print(get_console_default_encoding())
@@ -0,0 +1,51 @@
1
+ import ctypes
2
+ import locale
3
+ import sys
4
+
5
+ def get_cp0_value():
6
+ """
7
+ 获取 CP0 对应的实际系统默认 ANSI 代码页编号
8
+ CP0 在 Windows 下等价于 CP_ACP (ANSI Code Page)
9
+ 兼容 Python 3.15+,移除 getdefaultlocale() 弃用警告
10
+ """
11
+
12
+ # 核心:调用 Windows API 获取 CP0 对应的实际代码页编号
13
+ kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
14
+ cp0_number = kernel32.GetACP()
15
+
16
+ # 替代弃用的 getdefaultlocale():分版本获取编码名称
17
+ if sys.version_info >= (3, 11):
18
+ # Python 3.11+ 推荐使用 getencoding()
19
+ try:
20
+ encoding_name = locale.getencoding()
21
+ except Exception:
22
+ encoding_name = f'cp{cp0_number}'
23
+ else:
24
+ # 兼容低版本 Python
25
+ try:
26
+ encoding_name = locale.getdefaultlocale()[1]
27
+ except (ValueError, IndexError):
28
+ encoding_name = f'cp{cp0_number}'
29
+
30
+ # 统一修正编码名称(如 gb2312 -> gbk,保持和 CP936 对应)
31
+ encoding_map = {
32
+ 'gb2312': 'gbk',
33
+ 'cp936': 'gbk',
34
+ 'cp1252': 'cp1252',
35
+ 'cp950': 'big5'
36
+ }
37
+ encoding_name = encoding_map.get(encoding_name.lower(), encoding_name)
38
+
39
+ return {
40
+ 'cp0_number': cp0_number,
41
+ 'encoding_name': encoding_name,
42
+ 'full_name': f'CP{cp0_number} ({encoding_name})'
43
+ }
44
+
45
+ # 测试调用
46
+ if __name__ == "__main__":
47
+ cp0_info = get_cp0_value()
48
+ print("CP0 对应的实际编码信息:")
49
+ print(f"- 代码页编号: {cp0_info['cp0_number']}")
50
+ print(f"- 编码名称: {cp0_info['encoding_name']}")
51
+ print(f"- 完整标识: {cp0_info['full_name']}")
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: console-default-encoding
3
+ Version: 0.0.1
4
+ Summary: get default encoding in current console in python.
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Author: GGN_2015
8
+ Author-email: neko@jlulug.org
9
+ Requires-Python: >=3.10
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Description-Content-Type: text/markdown
18
+
19
+ # console-default-encoding
20
+ get default encoding in current console in python.
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ pip install console-default-encoding
26
+ ```
27
+
28
+ ## Usage
29
+
30
+ ```python
31
+ import console_default_encoding
32
+
33
+ # utf-8, gbk ...
34
+ print(console_default_encoding.get_console_default_encoding())
35
+ ```
36
+
@@ -0,0 +1,7 @@
1
+ console_default_encoding/__init__.py,sha256=zZzJnfxOb-rMA-Khly_y6s1-oO6SGUxW2PKjHTljDyw,104
2
+ console_default_encoding/con_de.py,sha256=6cChXDWP3O8QL8aT1Yqk20nvWsc0mVx-7tA9c_ElXx4,3562
3
+ console_default_encoding/get_cp0.py,sha256=H0bWr9bB4ouyu-ZTRq_6gCGyhta6dDszuY12r_qoU7s,1718
4
+ console_default_encoding-0.0.1.dist-info/licenses/LICENSE,sha256=gmkEFqkF3KJjRnhXGoLSfX4xXtfPHT1ghq3YgCF7B3w,1086
5
+ console_default_encoding-0.0.1.dist-info/METADATA,sha256=JW8xAcYg-GfhWMO8wgBAToT5DyPuSlndmFSJ3pAfhvQ,908
6
+ console_default_encoding-0.0.1.dist-info/WHEEL,sha256=kJCRJT_g0adfAJzTx2GUMmS80rTJIVHRCfG0DQgLq3o,88
7
+ console_default_encoding-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.3.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GGN_2015
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.