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>
最新发布