PS C:\Users\Administrator\Desktop> # PythonEnvRepair_Complete_Fix.ps1
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 1. 动态获取桌面路径(多级回退)
PS C:\Users\Administrator\Desktop> $desktopPath = @( >> [Environment]::GetFolderPath([Environment+SpecialFolder]::Desktop),
>> "C:\Users\Administrator\Desktop",
>> "C:\Users\Public\Desktop",
>> "C:\Windows\Desktop",
>> "C:\Desktop"
>> ) | Where-Object { Test-Path $_ } | Select-Object -First 1
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> if (-not $desktopPath) {
>> $desktopPath = "C:\Temp"
>> Write-Host "⚠️ 警告: 使用备用路径: $desktopPath" -ForegroundColor Yellow
>> }
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 2. 设置全局编码(强制UTF-8)
PS C:\Users\Administrator\Desktop> [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
PS C:\Users\Administrator\Desktop> $env:PYTHONUTF8 = "1"
PS C:\Users\Administrator\Desktop> $env:PYTHONIOENCODING = "utf-8"
PS C:\Users\Administrator\Desktop> [Environment]::SetEnvironmentVariable("PYTHONUTF8", "1", "Machine")
PS C:\Users\Administrator\Desktop> [Environment]::SetEnvironmentVariable("PYTHONIOENCODING", "utf-8", "Machine")
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 3. 终极修复函数
PS C:\Users\Administrator\Desktop> function global:Repair-PythonEnvironment {
>> param(
>> [string]$PythonPath = "E:\Python310",
>> [switch]$Force = $false
>> )
>>
>> # 验证Python安装
>> $pythonExe = Join-Path $PythonPath "python.exe"
>> if (-not (Test-Path $pythonExe)) {
>> Write-Host "❌ 错误: 找不到python.exe: $pythonExe" -ForegroundColor Red
>> return $false
>> }
>>
>> # 获取Python版本信息
>> $versionInfo = & $pythonExe -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"
>> $shortVersion = & $pythonExe -c "import sys; print(f'{sys.version_info.major}{sys.version_info.minor}')"
>>
>> # 创建site-packages目录(如果不存在)
>> $sitePackages = Join-Path $PythonPath "Lib\site-packages"
>> if (-not (Test-Path $sitePackages)) {
>> New-Item -ItemType Directory -Path $sitePackages -Force | Out-Null
>> Write-Host "创建site-packages目录: $sitePackages" -ForegroundColor Cyan
>> }
>>
>> # 设置持久化环境变量
>> [Environment]::SetEnvironmentVariable("DESKTOP_PATH", $desktopPath, "User")
>> [Environment]::SetEnvironmentVariable("DESKTOP_PATH", $desktopPath, "Machine")
>> $env:DESKTOP_PATH = $desktopPath
>>
>> # 创建增强版sitecustomize.py
>> $sitecustomizeContent = @"
>> import sys
>> import os
>> import site
>> import traceback
>> import importlib.util
>> import logging
>>
>> # 配置日志
>> log_path = os.path.join(os.path.expanduser('~'), 'python_env_fix.log')
>> logging.basicConfig(
>> filename=log_path,
>> level=logging.INFO,
>> format='%(asctime)s - %(levelname)s - %(message)s',
>> encoding='utf-8'
>> )
>>
>> logger = logging.getLogger('PythonEnvFix')
>>
>> def ensure_path(path, priority=0):
>> """确保路径在sys.path中"""
>> abs_path = os.path.abspath(path)
>> logger.info(f"处理路径: {abs_path}")
>>
>> # 创建目录(如果不存在)
>> if not os.path.exists(abs_path):
>> try:
>> os.makedirs(abs_path)
>> logger.info(f"创建目录: {abs_path}")
>> except Exception as e:
>> logger.error(f"创建目录失败: {abs_path}, 错误: {str(e)}")
>> return False
>>
>> # 添加路径到sys.path
>> if abs_path not in sys.path:
>> try:
>> if priority == 0:
>> sys.path.insert(0, abs_path) # 最高优先级
>> else:
>> sys.path.append(abs_path) # 最低优先级
>> logger.info(f"添加路径到sys.path: 优先级={priority}")
>> except Exception as e:
>> logger.error(f"添加路径到sys.path失败: {str(e)}")
>>
>> # 使用site模块添加路径
>> try:
>> site.addsitedir(abs_path)
>> logger.info(f"使用site.addsitedir添加路径")
>> except Exception as e:
>> logger.error(f"site.addsitedir失败: {str(e)}")
>>
>> # 验证路径可导入性
>> try:
>> importlib.util.find_spec('__init__', [abs_path])
>> logger.info("路径可导入验证成功")
>> except ImportError:
>> logger.warning(f"路径不可导入: {abs_path}")
>>
>> return True
>>
>> # 主修复逻辑
>> try:
>> desktop_path = os.environ.get('DESKTOP_PATH', '')
>> if desktop_path:
>> logger.info(f"开始修复路径: {desktop_path}")
>> if ensure_path(desktop_path, priority=0):
>> logger.info(f"路径添加成功: {desktop_path}")
>> else:
>> logger.error(f"路径添加失败: {desktop_path}")
>> else:
>> logger.error("DESKTOP_PATH环境变量未设置")
>>
>> # 刷新模块缓存
>> sys.path_importer_cache.clear()
>> logger.info("模块缓存已刷新")
>>
>> except Exception as e:
>> logger.error(f"修复过程中发生错误: {str(e)}")
>> logger.error(traceback.format_exc())
>> "@
>>
>> $sitecustomizePath = Join-Path $sitePackages "sitecustomize.py"
>> Set-Content -Path $sitecustomizePath -Value $sitecustomizeContent -Encoding UTF8
>> Write-Host "创建sitecustomize.py: $sitecustomizePath" -ForegroundColor Cyan
>>
>> # 创建系统级.pth文件
>> $pthPath = Join-Path $sitePackages "desktop_path.pth"
>> Set-Content -Path $pthPath -Value $desktopPath -Encoding UTF8
>> Write-Host "创建系统级.pth文件: $pthPath" -ForegroundColor Cyan
>>
>> # 创建用户级.pth文件
>> $userSitePath = Join-Path $env:APPDATA "Python\Python$shortVersion\site-packages"
>>
>> if (-not (Test-Path $userSitePath)) {
>> New-Item -ItemType Directory -Path $userSitePath -Force | Out-Null
>> Write-Host "创建用户site-packages目录: $userSitePath" -ForegroundColor Cyan
>> }
>>
>> $userPthPath = Join-Path $userSitePath "desktop_path.pth"
>> Set-Content -Path $userPthPath -Value $desktopPath -Encoding UTF8
>> Write-Host "创建用户级.pth文件: $userPthPath" -ForegroundColor Cyan
>>
>> # 在Python安装目录添加路径
>> $pythonPathFile = Join-Path $PythonPath "pythonpath.txt"
>> Set-Content -Path $pythonPathFile -Value $desktopPath -Encoding UTF8
>> Write-Host "创建Python路径文件: $pythonPathFile" -ForegroundColor Cyan
>>
>> Write-Host "✅ Python环境修复完成" -ForegroundColor Green
>> return $true
>> }
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 4. 全面诊断函数
PS C:\Users\Administrator\Desktop> function global:Test-PythonEnvironment {
>> param(
>> [string]$PythonPath = "E:\Python310",
>> [switch]$Detailed = $false
>> )
>>
>> $pythonExe = Join-Path $PythonPath "python.exe"
>> if (-not (Test-Path $pythonExe)) {
>> Write-Host "❌ 错误: 找不到python.exe: $pythonExe" -ForegroundColor Red
>> return $false
>> }
>>
>> # 确保环境变量传递
>> $env:DESKTOP_PATH = $desktopPath
>>
>> # 生成诊断脚本
>> $testScript = @"
>> import sys
>> import os
>> import site
>> import traceback
>> import importlib.util
>> import platform
>> import json
>>
>> # 收集诊断数据
>> diagnostic_data = {
>> "system_info": {
>> "python_version": sys.version,
>> "platform": sys.platform,
>> "executable": sys.executable,
>> "default_encoding": sys.getdefaultencoding(),
>> "filesystem_encoding": sys.getfilesystemencoding(),
>> "os_name": os.name,
>> "os_version": platform.platform(),
>> "desktop_path": os.environ.get('DESKTOP_PATH', '')
>> },
>> "environment_vars": {
>> "PYTHONPATH": os.environ.get('PYTHONPATH', ''),
>> "PYTHONHOME": os.environ.get('PYTHONHOME', ''),
>> "PATH": os.environ.get('PATH', '')
>> },
>> "path_analysis": {
>> "desktop_path_exists_in_sys_path": False,
>> "desktop_path_position": -1,
>> "sys_path": sys.path
>> },
>> "module_import_test": {"success": False, "error": ""},
>> "file_operation_test": {"success": False, "error": ""},
>> "site_packages_analysis": []
>> }
>>
>> # 路径分析
>> desktop_path = diagnostic_data["system_info"]["desktop_path"]
>> if desktop_path:
>> desktop_abs = os.path.abspath(desktop_path)
>> if desktop_abs in [os.path.abspath(p) for p in sys.path]:
>> diagnostic_data["path_analysis"]["desktop_path_exists_in_sys_path"] = True
>> diagnostic_data["path_analysis"]["desktop_path_position"] = [
>> os.path.abspath(p) for p in sys.path
>> ].index(desktop_abs)
>>
>> # 模块导入测试
>> if desktop_path:
>> test_module = os.path.join(desktop_path, "diagnostic_test_module.py")
>> try:
>> with open(test_module, 'w', encoding='utf-8') as f:
>> f.write("def test_function():\n return '诊断测试成功'")
>>
>> spec = importlib.util.spec_from_file_location("diagnostic_test_module", test_module)
>> module = importlib.util.module_from_spec(spec)
>> spec.loader.exec_module(module)
>> result = module.test_function()
>> diagnostic_data["module_import_test"]["success"] = True
>> diagnostic_data["module_import_test"]["result"] = result
>> except Exception as e:
>> diagnostic_data["module_import_test"]["error"] = str(e)
>> diagnostic_data["module_import_test"]["traceback"] = traceback.format_exc()
>> finally:
>> try:
>> os.remove(test_module)
>> except:
>> pass
>>
>> # 文件操作测试
>> if desktop_path:
>> test_file = os.path.join(desktop_path, "diagnostic_test_file.txt")
>> try:
>> with open(test_file, 'w', encoding='utf-8') as f:
>> f.write("Python环境诊断测试文件")
>>
>> if os.path.exists(test_file):
>> diagnostic_data["file_operation_test"]["success"] = True
>> os.remove(test_file)
>> except Exception as e:
>> diagnostic_data["file_operation_test"]["error"] = str(e)
>> diagnostic_data["file_operation_test"]["traceback"] = traceback.format_exc()
>>
>> # site-packages分析
>> for path in sys.path:
>> if 'site-packages' in path and os.path.isdir(path):
>> dir_info = {
>> "path": path,
>> "pth_files": [],
>> "sitecustomize_exists": os.path.exists(os.path.join(path, "sitecustomize.py"))
>> }
>>
>> try:
>> for file in os.listdir(path):
>> if file.endswith('.pth'):
>> pth_path = os.path.join(path, file)
>> with open(pth_path, 'r', encoding='utf-8') as f:
>> content = f.read().strip()
>> dir_info["pth_files"].append({
>> "name": file,
>> "content": content
>> })
>> except Exception as e:
>> dir_info["error"] = str(e)
>>
>> diagnostic_data["site_packages_analysis"].append(dir_info)
>>
>> # 输出JSON格式结果
>> print(json.dumps(diagnostic_data, indent=2, ensure_ascii=False))
>> "@
>>
>> $tempScript = Join-Path $env:TEMP "python_diagnostic_$(Get-Date -Format 'yyyyMMdd_HHmmss').py"
>> Set-Content -Path $tempScript -Value $testScript -Encoding UTF8
>>
>> Write-Host "`n🚀 运行全面环境诊断..." -ForegroundColor Cyan
>> try {
>> $result = & $pythonExe $tempScript | ConvertFrom-Json
>>
>> # 显示摘要报告
>> Write-Host "`n=== 诊断报告摘要 ===" -ForegroundColor Green
>> Write-Host "Python版本: $($result.system_info.python_version.split()[0])"
>> Write-Host "系统平台: $($result.system_info.platform)"
>> Write-Host "桌面路径: $($result.system_info.desktop_path)"
>> Write-Host "路径存在: $($result.path_analysis.desktop_path_exists_in_sys_path)"
>> Write-Host "模块导入: $($result.module_import_test.success)"
>> Write-Host "文件操作: $($result.file_operation_test.success)"
>>
>> if ($Detailed) {
>> Write-Host "`n=== 详细诊断数据 ===" -ForegroundColor Yellow
>> $result | Format-List | Out-String | Write-Host
>> }
>>
>> return $true
>> } catch {
>> Write-Host "❌ 诊断执行失败: $_" -ForegroundColor Red
>> return $false
>> } finally {
>> Remove-Item $tempScript -ErrorAction SilentlyContinue
>> }
>> }
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 5. 主执行逻辑
PS C:\Users\Administrator\Desktop> param(
>> [string]$PythonPath = "E:\Python310",
>> [switch]$DiagnoseOnly = $false
>> )
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 执行修复或诊断
PS C:\Users\Administrator\Desktop> if ($DiagnoseOnly) {
>> Test-PythonEnvironment -PythonPath $PythonPath -Detailed
>> } else {
>> if (Repair-PythonEnvironment -PythonPath $PythonPath) {
>> Write-Host "`n✅ 修复完成!运行诊断测试..." -ForegroundColor Green
>> Test-PythonEnvironment -PythonPath $PythonPath
>> }
>> }
创建sitecustomize.py: E:\Python310\Lib\site-packages\sitecustomize.py
创建系统级.pth文件: E:\Python310\Lib\site-packages\desktop_path.pth
创建用户级.pth文件: C:\Users\Administrator\AppData\Roaming\Python\Python310\site-packages\desktop_path.pth
创建Python路径文件: E:\Python310\pythonpath.txt
✅ Python环境修复完成
✅ 修复完成!运行诊断测试...
🚀 运行全面环境诊断...
=== 诊断报告摘要 ===
Python版本: 3.10.10
系统平台: win32
桌面路径: C:\Users\Administrator\Desktop
路径存在: False
模块导入: True
文件操作: True
True
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 6. 保存脚本
PS C:\Users\Administrator\Desktop> $scriptContent = $MyInvocation.MyCommand.Definition
PS C:\Users\Administrator\Desktop> $scriptName = "PythonEnvRepair_Complete_Fix.ps1"
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> @(
>> [Environment]::GetFolderPath([Environment+SpecialFolder]::Desktop),
>> [Environment]::GetFolderPath([Environment+SpecialFolder]::MyDocuments),
>> "C:\Temp",
>> $env:USERPROFILE,
>> "C:\Scripts"
>> ) | Where-Object { Test-Path $_ } | ForEach-Object {
>> $scriptPath = Join-Path $_ $scriptName
>> Set-Content -Path $scriptPath -Value $scriptContent -Encoding UTF8
>> Write-Host "脚本已保存到: $scriptPath" -ForegroundColor Cyan
>> }
脚本已保存到: C:\Users\Administrator\Desktop\PythonEnvRepair_Complete_Fix.ps1
脚本已保存到: C:\Users\Administrator\Documents\PythonEnvRepair_Complete_Fix.ps1
脚本已保存到: C:\Temp\PythonEnvRepair_Complete_Fix.ps1
脚本已保存到: C:\Users\Administrator\PythonEnvRepair_Complete_Fix.ps1
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 7. 最终提示
PS C:\Users\Administrator\Desktop> Write-Host "`n🔧 后续操作建议:"
🔧 后续操作建议:
PS C:\Users\Administrator\Desktop> Write-Host "1. 重启所有Python相关进程" -ForegroundColor Yellow
1. 重启所有Python相关进程
PS C:\Users\Administrator\Desktop> Write-Host "2. 重启终端使环境变量生效" -ForegroundColor Yellow
2. 重启终端使环境变量生效
PS C:\Users\Administrator\Desktop> Write-Host "3. 定期运行诊断: Test-PythonEnvironment -PythonPath '$PythonPath'" -ForegroundColor Cyan
3. 定期运行诊断: Test-PythonEnvironment -PythonPath 'E:\Python310'
PS C:\Users\Administrator\Desktop> .\PythonEnvRepair_Complete_Fix.ps1 -PythonPath "E:\Python310"
PS C:\Users\Administrator\Desktop> .\PythonEnvRepair_Complete_Fix.ps1 -PythonPath "E:\Python310" -DiagnoseOnly -Detailed
PS C:\Users\Administrator\Desktop> Get-Content ~/python_env_fix.log
Get-Content : 找不到路径“C:\Users\Administrator\python_env_fix.log”,因为该路径不存在。
所在位置 行:1 字符: 1
+ Get-Content ~/python_env_fix.log
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Users\Admini...hon_env_fix.log:String) [Get-Content], ItemNotFoundEx
ception
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
PS C:\Users\Administrator\Desktop> python -c "import sys; print('桌面路径在sys.path中' if r'C:\Users\Administrator\Desktop' in sys.path else '路径未添加')"
路径未添加
PS C:\Users\Administrator\Desktop> # PythonEnvRepair_Centralized.ps1
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 1. 定义集中存储目录(优先E盘,其次C盘)
PS C:\Users\Administrator\Desktop> $centralStorage = @("E:\PythonEnvFix", "C:\PythonEnvFix") | Where-Object {
>> -not (Test-Path $_) -or (Test-Path $_ -PathType Container)
>> } | Select-Object -First 1
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 创建存储目录(如果不存在)
PS C:\Users\Administrator\Desktop> if (-not (Test-Path $centralStorage)) {
>> New-Item -ItemType Directory -Path $centralStorage -Force | Out-Null
>> Write-Host "创建集中存储目录: $centralStorage" -ForegroundColor Cyan
>> }
创建集中存储目录: E:\PythonEnvFix
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 2. 设置桌面路径(仅用于Python环境)
PS C:\Users\Administrator\Desktop> $desktopPath = [Environment]::GetFolderPath([Environment+SpecialFolder]::Desktop)
PS C:\Users\Administrator\Desktop> if (-not (Test-Path $desktopPath)) {
>> $desktopPath = Join-Path $centralStorage "Desktop"
>> New-Item -ItemType Directory -Path $desktopPath -Force | Out-Null
>> }
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 3. 核心修复函数(无桌面文件生成)
PS C:\Users\Administrator\Desktop> function global:Repair-PythonEnvironment {
>> param(
>> [string]$PythonPath = "E:\Python310",
>> [switch]$Silent = $false
>> )
>>
>> # 验证Python安装
>> $pythonExe = Join-Path $PythonPath "python.exe"
>> if (-not (Test-Path $pythonExe)) {
>> Write-Host "❌ 错误: 找不到python.exe: $pythonExe" -ForegroundColor Red
>> return $false
>> }
>>
>> # 创建修复日志目录
>> $logDir = Join-Path $centralStorage "Logs"
>> if (-not (Test-Path $logDir)) {
>> New-Item -ItemType Directory -Path $logDir -Force | Out-Null
>> }
>>
>> # 生成日志文件路径(集中存储)
>> $logFile = Join-Path $logDir "PythonFix_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
>>
>> # 创建sitecustomize.py(内存中生成)
>> $sitecustomizeContent = @"
>> import sys
>> import os
>> import site
>> import logging
>>
>> # 配置日志(集中存储)
>> log_dir = r"$logDir"
>> if not os.path.exists(log_dir):
>> try:
>> os.makedirs(log_dir)
>> except:
>> log_dir = os.path.expanduser("~")
>>
>> log_file = os.path.join(log_dir, "python_env_fix.log")
>> logging.basicConfig(
>> filename=log_file,
>> level=logging.INFO,
>> format='%(asctime)s - %(levelname)s - %(message)s',
>> encoding='utf-8'
>> )
>>
>> logger = logging.getLogger('PythonEnvFix')
>>
>> # 添加桌面路径到系统路径
>> desktop_path = r"$desktopPath"
>> if desktop_path not in sys.path:
>> sys.path.insert(0, desktop_path)
>> logger.info(f"添加桌面路径到sys.path: {desktop_path}")
>>
>> # 添加集中存储目录到路径
>> if r"$centralStorage" not in sys.path:
>> sys.path.append(r"$centralStorage")
>> logger.info(f"添加集中存储路径: $centralStorage")
>>
>> # 刷新模块缓存
>> sys.path_importer_cache.clear()
>> "@
>>
>> # 直接写入Python的site-packages(不生成中间文件)
>> $sitePackages = Join-Path $PythonPath "Lib\site-packages"
>> $sitecustomizePath = Join-Path $sitePackages "sitecustomize.py"
>> Set-Content -Path $sitecustomizePath -Value $sitecustomizeContent -Encoding UTF8
>>
>> # 创建.pth文件(直接指向桌面路径)
>> $pthPath = Join-Path $sitePackages "desktop_path.pth"
>> Set-Content -Path $pthPath -Value $desktopPath -Encoding UTF8
>>
>> if (-not $Silent) {
>> Write-Host "✅ Python环境修复完成" -ForegroundColor Green
>> Write-Host "日志文件: $logFile" -ForegroundColor Cyan
>> }
>>
>> return $true
>> }
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 4. 诊断函数(无文件生成)
PS C:\Users\Administrator\Desktop> function global:Test-PythonEnvironment {
>> param(
>> [string]$PythonPath = "E:\Python310"
>> )
>>
>> $pythonExe = Join-Path $PythonPath "python.exe"
>> if (-not (Test-Path $pythonExe)) {
>> Write-Host "❌ 错误: 找不到python.exe: $pythonExe" -ForegroundColor Red
>> return $false
>> }
>>
>> # 直接在内存中执行诊断
>> $diagnosticScript = @"
>> import sys
>> import os
>> import json
>>
>> result = {
>> "status": "success",
>> "desktop_path": r"$desktopPath",
>> "in_sys_path": r"$desktopPath" in sys.path,
>> "central_storage": r"$centralStorage",
>> "central_in_path": r"$centralStorage" in sys.path,
>> "sys_path": sys.path
>> }
>>
>> print(json.dumps(result))
>> "@
>>
>> # 直接通过命令行执行(不生成文件)
>> $diagnosticResult = & $pythonExe -c $diagnosticScript | ConvertFrom-Json
>>
>> # 显示结果
>> Write-Host "`n=== 环境诊断报告 ===" -ForegroundColor Green
>> Write-Host "桌面路径: $($diagnosticResult.desktop_path)"
>> Write-Host "在sys.path中: $($diagnosticResult.in_sys_path)"
>> Write-Host "集中存储路径: $($diagnosticResult.central_storage)"
>> Write-Host "在sys.path中: $($diagnosticResult.central_in_path)"
>>
>> if ($diagnosticResult.in_sys_path -and $diagnosticResult.central_in_path) {
>> Write-Host "✅ 环境状态正常" -ForegroundColor Green
>> } else {
>> Write-Host "⚠️ 环境需要修复" -ForegroundColor Yellow
>> Write-Host "运行命令: Repair-PythonEnvironment -PythonPath '$PythonPath'" -ForegroundColor Cyan
>> }
>>
>> return $true
>> }
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 5. 清理函数(删除多余文件)
PS C:\Users\Administrator\Desktop> function global:Clean-PythonFixFiles {
>> # 删除可能存在的旧脚本
>> $locations = @(
>> [Environment]::GetFolderPath([Environment+SpecialFolder]::Desktop),
>> [Environment]::GetFolderPath([Environment+SpecialFolder]::MyDocuments),
>> "C:\Temp",
>> $env:USERPROFILE
>> )
>>
>> $patterns = @("*PythonEnvRepair*.ps1", "*PythonEnvFix*.log")
>>
>> foreach ($location in $locations) {
>> if (Test-Path $location) {
>> foreach ($pattern in $patterns) {
>> Get-ChildItem -Path $location -Filter $pattern -ErrorAction SilentlyContinue | ForEach-Object {
>> Remove-Item $_.FullName -Force
>> Write-Host "已删除: $($_.FullName)" -ForegroundColor Yellow
>> }
>> }
>> }
>> }
>>
>> Write-Host "✅ 清理完成" -ForegroundColor Green
>> }
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 6. 主执行逻辑
PS C:\Users\Administrator\Desktop> param(
>> [string]$PythonPath = "E:\Python310",
>> [switch]$CleanOnly = $false
>> )
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 执行清理或修复
PS C:\Users\Administrator\Desktop> if ($CleanOnly) {
>> Clean-PythonFixFiles
>> } else {
>> # 先清理旧文件
>> Clean-PythonFixFiles -ErrorAction SilentlyContinue
>>
>> # 执行修复
>> if (Repair-PythonEnvironment -PythonPath $PythonPath -Silent) {
>> Write-Host "`n✅ 修复完成!运行诊断测试..." -ForegroundColor Green
>> Test-PythonEnvironment -PythonPath $PythonPath
>> }
>> }
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Complete_Fix.ps1
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Complete_Fixed.ps1
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Final_Complete.ps1
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Final_Corrected.ps1
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Final_Fix.ps1
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Final_Solution.ps1
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Full.ps1
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Full_Final.ps1
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Full_Final_Fixed.ps1
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Full_Fixed.ps1
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Full_Optimized.ps1
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Guaranteed_Fix.ps1
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Ultimate_Fix.ps1
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Ultimate_Fixed.ps1
已删除: C:\Users\Administrator\Desktop\PythonEnvRepair_Ultimate_Solution.ps1
已删除: C:\Users\Administrator\Documents\PythonEnvRepair_Complete_Fix.ps1
已删除: C:\Temp\PythonEnvRepair_Complete_Fix.ps1
已删除: C:\Temp\PythonEnvRepair_Complete_Fixed.ps1
已删除: C:\Temp\PythonEnvRepair_Final_Complete.ps1
已删除: C:\Temp\PythonEnvRepair_Final_Corrected.ps1
已删除: C:\Temp\PythonEnvRepair_Final_Fix.ps1
已删除: C:\Temp\PythonEnvRepair_Final_Solution.ps1
已删除: C:\Temp\PythonEnvRepair_Full_Final.ps1
已删除: C:\Temp\PythonEnvRepair_Full_Final_Fixed.ps1
已删除: C:\Temp\PythonEnvRepair_Full_Fixed.ps1
已删除: C:\Temp\PythonEnvRepair_Full_Optimized.ps1
已删除: C:\Temp\PythonEnvRepair_Guaranteed_Fix.ps1
已删除: C:\Temp\PythonEnvRepair_Ultimate_Fix.ps1
已删除: C:\Temp\PythonEnvRepair_Ultimate_Fixed.ps1
已删除: C:\Temp\PythonEnvRepair_Ultimate_Solution.ps1
已删除: C:\Users\Administrator\PythonEnvRepair_Complete_Fix.ps1
已删除: C:\Users\Administrator\PythonEnvRepair_Final_Fix.ps1
✅ 清理完成
✅ 修复完成!运行诊断测试...
File "<string>", line 5
result = {
^
SyntaxError: '{' was never closed
=== 环境诊断报告 ===
桌面路径:
在sys.path中:
集中存储路径:
在sys.path中:
⚠️ 环境需要修复
运行命令: Repair-PythonEnvironment -PythonPath 'E:\Python310'
True
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 7. 保存主脚本到集中目录(不在桌面)
PS C:\Users\Administrator\Desktop> $scriptPath = Join-Path $centralStorage "PythonEnvRepair_Centralized.ps1"
PS C:\Users\Administrator\Desktop> Set-Content -Path $scriptPath -Value $MyInvocation.MyCommand.Definition -Encoding UTF8
PS C:\Users\Administrator\Desktop> Write-Host "主脚本位置: $scriptPath" -ForegroundColor Cyan
主脚本位置: E:\PythonEnvFix\PythonEnvRepair_Centralized.ps1
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 8. 最终提示
PS C:\Users\Administrator\Desktop> Write-Host "`n💻 环境管理命令:" -ForegroundColor Magenta
💻 环境管理命令:
PS C:\Users\Administrator\Desktop> Write-Host "1. 修复环境: Repair-PythonEnvironment -PythonPath '$PythonPath'" -ForegroundColor Cyan
1. 修复环境: Repair-PythonEnvironment -PythonPath 'E:\Python310'
PS C:\Users\Administrator\Desktop> Write-Host "2. 诊断环境: Test-PythonEnvironment -PythonPath '$PythonPath'" -ForegroundColor Cyan
2. 诊断环境: Test-PythonEnvironment -PythonPath 'E:\Python310'
PS C:\Users\Administrator\Desktop> Write-Host "3. 清理文件: Clean-PythonFixFiles" -ForegroundColor Yellow
3. 清理文件: Clean-PythonFixFiles
PS C:\Users\Administrator\Desktop> Write-Host "`n所有文件集中在: $centralStorage" -ForegroundColor Green
所有文件集中在: E:\PythonEnvFix
PS C:\Users\Administrator\Desktop> .\PythonEnvRepair_Centralized.ps1 -PythonPath "E:\Python310"
.\PythonEnvRepair_Centralized.ps1 : 无法将“.\PythonEnvRepair_Centralized.ps1”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,
请确保路径正确,然后再试一次。
所在位置 行:1 字符: 1
+ .\PythonEnvRepair_Centralized.ps1 -PythonPath "E:\Python310"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (.\PythonEnvRepair_Centralized.ps1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\Users\Administrator\Desktop> # 修复环境
PS C:\Users\Administrator\Desktop> Repair-PythonEnvironment -PythonPath "E:\Python310"
✅ Python环境修复完成
日志文件: E:\PythonEnvFix\Logs\PythonFix_20250822_225714.log
True
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 诊断环境
PS C:\Users\Administrator\Desktop> Test-PythonEnvironment -PythonPath "E:\Python310"
File "<string>", line 5
result = {
^
SyntaxError: '{' was never closed
=== 环境诊断报告 ===
桌面路径:
在sys.path中:
集中存储路径:
在sys.path中:
⚠️ 环境需要修复
运行命令: Repair-PythonEnvironment -PythonPath 'E:\Python310'
True
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 清理旧文件
PS C:\Users\Administrator\Desktop> Clean-PythonFixFiles
✅ 清理完成
PS C:\Users\Administrator\Desktop> # 立即清理桌面Python相关文件
PS C:\Users\Administrator\Desktop> Get-ChildItem -Path $env:USERPROFILE\Desktop -Filter *PythonEnv* -File | Remove-Item -Force
PS C:\Users\Administrator\Desktop> Get-ChildItem -Path $env:USERPROFILE\Desktop -Filter *PythonFix* -File | Remove-Item -Force
PS C:\Users\Administrator\Desktop> Write-Host "✅ 桌面已清理" -ForegroundColor Green
✅ 桌面已清理
PS C:\Users\Administrator\Desktop> # 验证桌面路径是否在Python路径中
PS C:\Users\Administrator\Desktop> python -c "import sys; print('✅ 桌面路径在sys.path中' if r'C:\Users\Administrator\Desktop' in sys.path else '❌ 路径未添加')"
❌ 路径未添加
PS C:\Users\Administrator\Desktop>
PS C:\Users\Administrator\Desktop> # 检查集中存储路径
PS C:\Users\Administrator\Desktop> python -c "import sys; print(f'集中存储路径: {[p for p in sys.path if p.startswith(\"E:\PythonEnvFix\")][0]}')"
File "<string>", line 1
import sys; print(f'集中存储路径: {[p for p in sys.path if p.startswith(" E:\PythonEnvFix\)][0]}')
^
SyntaxError: f-string expression part cannot include a backslash
PS C:\Users\Administrator\Desktop>