python 的sitecustomize.py

本文介绍如何在Python中通过sitecustomize.py脚本设置默认编码为utf-8,避免每次使用时手动设置。

  • sitecustomize.py 是python中的一个特殊脚本,可以放在目录下的任意位置,不过一般放在home\Lib\site-packages下面,当python开始运行时会先运行该脚本中的代码,因此可以用来设置一些default的东西。
  • 一个用途就是用来设置python的默认编码,在import sys后,可以使用sys.getdefaultencoding()函数查看默认编码,如果你想使用utf-8成为默认编码,又不愿意每次都来设置一下,可以在sitecustomize.py中放入以下代码
# set system default encoding: utf-8
import sys

reload(sys) # 可能不需要
sys.setdefaultencoding('utf-8')

这样python默认编码就变成了utf-8,并且以后无需在设置。

注:信息来源为 Dive Into Python

PS C:\Users\Administrator\Desktop> function Optimize-PthFiles { >> param( >> [string]$PythonPath = "E:\Python310" >> ) >> >> $sitePackages = "$PythonPath\Lib\site-packages" >> >> # 1. 删除旧版sitecustomize.py以避免冲突 >> $sitePath = python -c "import site; print(site.__file__)" 2>$null >> $siteDir = [System.IO.Path]::GetDirectoryName($sitePath) >> $siteCustomizePath = "$siteDir\sitecustomize.py" >> if (Test-Path $siteCustomizePath) { >> Remove-Item $siteCustomizePath -Force >> Write-Host "🧹 清理旧版sitecustomize.py" -ForegroundColor Yellow >> } >> >> # 2. 创建纯ASCII的.pth文件内容(避免编码问题) >> $usefulContent = @' >> # PYTHON ENVIRONMENT HELPER >> import sys, os, datetime >> >> def log_environment_change(): >> timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") >> log_path = os.path.join(os.path.dirname(__file__), "environment_changes.log") >> with open(log_path, "a") as f: >> f.write(f"[{timestamp}] Environment modified via {__file__}\n") >> >> DEV_TOOLS = { >> "clean": "python -m pip cache purge", >> "update": "python -m pip list --outdated", >> "check": "python -m pip check" >> } >> >> def check_conflicts(): >> try: >> from pip._internal.utils import compatibility_tags >> return "Package compatibility: OK" >> except ImportError as e: >> return f"Package conflict: {str(e)}" >> >> if not hasattr(sys, 'pth_helper_initialized'): >> log_environment_change() >> sys.pth_helper_initialized = True >> '@ >> >> # 3. 创建/更新.pth文件 >> $newPthPath = "$sitePackages\environment-helper.pth" >> [System.IO.File]::WriteAllText($newPthPath, $usefulContent, [System.Text.Encoding]::ASCII) >> Write-Host "✨ 创建环境助手文件: $newPthPath" -ForegroundColor Cyan >> >> # 4. 创建纯ASCII的sitecustomize.py >> $siteCustomizeContent = @' >> import sys >> import os >> >> def enhanced_pth_handler(pth_file): >> if "environment-helper.pth" in pth_file: >> try: >> if not hasattr(sys, 'env_helper'): >> from environment_helper import EnvironmentHelper >> sys.env_helper = EnvironmentHelper() >> print("[ENV HELPER] Environment helper activated") >> return True >> except: >> pass >> return True >> >> if hasattr(sys, "__orig_site_pth_handler"): >> sys._pth_handler = enhanced_pth_handler >> else: >> sys.__orig_site_pth_handler = sys._pth_handler >> sys._pth_handler = enhanced_pth_handler >> '@ >> >> [System.IO.File]::WriteAllText($siteCustomizePath, $siteCustomizeContent, [System.Text.Encoding]::ASCII) >> Write-Host "🔧 创建sitecustomize.py: $siteCustomizePath" -ForegroundColor Cyan >> >> # 5. 创建纯ASCII的环境助手模块 >> $helperScript = @' >> import sys >> import os >> import subprocess >> import datetime >> >> class EnvironmentHelper: >> @staticmethod >> def get_status(): >> return { >> "python_version": sys.version.split()[0], >> "platform": sys.platform, >> "executable": sys.executable, >> "timestamp": datetime.datetime.now().isoformat() >> } >> >> @staticmethod >> def list_tools(): >> return { >> "clean": "Clean pip cache", >> "update": "Check for updates", >> "check": "Verify dependencies" >> } >> >> @staticmethod >> def run_tool(tool_name): >> commands = { >> "clean": [sys.executable, "-m", "pip", "cache", "purge"], >> "update": [sys.executable, "-m", "pip", "list", "--outdated"], >> "check": [sys.executable, "-m", "pip", "check"] >> } >> >> if tool_name in commands: >> print(f"Running tool: {tool_name}") >> return subprocess.call(commands[tool_name]) >> else: >> print(f"Unknown tool: {tool_name}") >> return 1 >> '@ >> >> $helperPath = "$sitePackages\environment_helper.py" >> [System.IO.File]::WriteAllText($helperPath, $helperScript, [System.Text.Encoding]::ASCII) >> Write-Host "📦 创建环境助手模块: $helperPath" -ForegroundColor Cyan >> >> # 6. 验证安装 >> Write-Host "🔄 验证环境助手..." -ForegroundColor Cyan >> python -c "import sys; print('Environment helper status:', 'env_helper' in dir(sys))" >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> function Test-EnhancedEnvironment { >> param( >> [string]$PythonPath = "E:\Python310" >> ) >> >> # 测试助手功能 >> $testOutput = python -c @" >> try: >> import sys >> if hasattr(sys, 'env_helper'): >> print('Environment helper status: OK') >> print('Python version:', sys.env_helper.get_status()['python_version']) >> print('Available tools:', list(sys.env_helper.list_tools().keys())) >> else: >> print('Environment helper status: NOT FOUND') >> >> # 测试工具执行 >> print('Testing tool execution:') >> sys.env_helper.run_tool('check') >> except Exception as e: >> print(f'Test failed: {e}') >> "@ >> >> Write-Host $testOutput >> >> # 检查文件存在 >> $requiredFiles = @( >> "$PythonPath\Lib\site-packages\environment-helper.pth", >> "$PythonPath\Lib\site-packages\environment_helper.py", >> "$([System.IO.Path]::GetDirectoryName((python -c "import site; print(site.__file__)" 2>$null)))\sitecustomize.py" >> ) >> >> foreach ($file in $requiredFiles) { >> if (Test-Path $file) { >> Write-Host "✅ Found: $file" -ForegroundColor Green >> } else { >> Write-Host "❌ Missing: $file" -ForegroundColor Red >> } >> } >> } PS C:\Users\Administrator\Desktop> # 1. 清理环境(可选) PS C:\Users\Administrator\Desktop> python -c "import site; import os; os.remove(os.path.join(os.path.dirname(site.__file__), 'sitecustomize.py'))" Fatal Python error: init_import_site: Failed to import the site module Python runtime state: initialized Traceback (most recent call last): File "E:\Python310\lib\site.py", line 617, in <module> main() File "E:\Python310\lib\site.py", line 604, in main known_paths = addsitepackages(known_paths) File "E:\Python310\lib\site.py", line 387, in addsitepackages addsitedir(sitedir, known_paths) File "E:\Python310\lib\site.py", line 226, in addsitedir addpackage(sitedir, name, known_paths) File "E:\Python310\lib\site.py", line 179, in addpackage for n, line in enumerate(f): UnicodeDecodeError: 'gbk' codec can't decode byte 0xbf in position 2: illegal multibyte sequence PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 2. 运行优化脚本 PS C:\Users\Administrator\Desktop> Optimize-PthFiles -PythonPath "E:\Python310" 🧹 清理旧版sitecustomize.py ✨ 创建环境助手文件: E:\Python310\Lib\site-packages\environment-helper.pth 🔧 创建sitecustomize.py: \sitecustomize.py 📦 创建环境助手模块: E:\Python310\Lib\site-packages\environment_helper.py 🔄 验证环境助手... Fatal Python error: init_import_site: Failed to import the site module Python runtime state: initialized Traceback (most recent call last): File "E:\Python310\lib\site.py", line 617, in <module> main() File "E:\Python310\lib\site.py", line 604, in main known_paths = addsitepackages(known_paths) File "E:\Python310\lib\site.py", line 387, in addsitepackages addsitedir(sitedir, known_paths) File "E:\Python310\lib\site.py", line 226, in addsitedir addpackage(sitedir, name, known_paths) File "E:\Python310\lib\site.py", line 179, in addpackage for n, line in enumerate(f): UnicodeDecodeError: 'gbk' codec can't decode byte 0xbf in position 2: illegal multibyte sequence PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 3. 重启PowerShell会话 PS C:\Users\Administrator\Desktop> # 关闭当前窗口,重新打开 PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 4. 测试环境 PS C:\Users\Administrator\Desktop> Test-EnhancedEnvironment -PythonPath "E:\Python310" Fatal Python error: init_import_site: Failed to import the site module Python runtime state: initialized Traceback (most recent call last): File "E:\Python310\lib\site.py", line 617, in <module> main() File "E:\Python310\lib\site.py", line 604, in main known_paths = addsitepackages(known_paths) File "E:\Python310\lib\site.py", line 387, in addsitepackages addsitedir(sitedir, known_paths) File "E:\Python310\lib\site.py", line 226, in addsitedir addpackage(sitedir, name, known_paths) File "E:\Python310\lib\site.py", line 179, in addpackage for n, line in enumerate(f): UnicodeDecodeError: 'gbk' codec can't decode byte 0xbf in position 2: illegal multibyte sequence ✅ Found: E:\Python310\Lib\site-packages\environment-helper.pth ✅ Found: E:\Python310\Lib\site-packages\environment_helper.py ✅ Found: \sitecustomize.py PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 5. 使用助手功能 PS C:\Users\Administrator\Desktop> # 获取环境状态 PS C:\Users\Administrator\Desktop> python -c "import sys; print(sys.env_helper.get_status())" Fatal Python error: init_import_site: Failed to import the site module Python runtime state: initialized Traceback (most recent call last): File "E:\Python310\lib\site.py", line 617, in <module> main() File "E:\Python310\lib\site.py", line 604, in main known_paths = addsitepackages(known_paths) File "E:\Python310\lib\site.py", line 387, in addsitepackages addsitedir(sitedir, known_paths) File "E:\Python310\lib\site.py", line 226, in addsitedir addpackage(sitedir, name, known_paths) File "E:\Python310\lib\site.py", line 179, in addpackage for n, line in enumerate(f): UnicodeDecodeError: 'gbk' codec can't decode byte 0xbf in position 2: illegal multibyte sequence PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 运行依赖检查 PS C:\Users\Administrator\Desktop> python -c "import sys; sys.env_helper.run_tool('check')" Fatal Python error: init_import_site: Failed to import the site module Python runtime state: initialized Traceback (most recent call last): File "E:\Python310\lib\site.py", line 617, in <module> main() File "E:\Python310\lib\site.py", line 604, in main known_paths = addsitepackages(known_paths) File "E:\Python310\lib\site.py", line 387, in addsitepackages addsitedir(sitedir, known_paths) File "E:\Python310\lib\site.py", line 226, in addsitedir addpackage(sitedir, name, known_paths) File "E:\Python310\lib\site.py", line 179, in addpackage for n, line in enumerate(f): UnicodeDecodeError: 'gbk' codec can't decode byte 0xbf in position 2: illegal multibyte sequence PS C:\Users\Administrator\Desktop>
最新发布
08-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值