Powershell commands详解之Function "add-content/ac"

本文介绍Powershell中add-content命令的使用方法,通过不同示例展示如何向指定文件追加内容,包括普通文本、多国语言字符、当前日期等。

add-content, alias 为ac

帮助:

  可以通过get-help add-content, help ac, 或者help ac -full来得到帮助。

用法:

  add-content <path> <content>, path 为你需要写入内容的目的文件,如"c:/new.txt", content 为你要写入的内容。

用途:

  向指定文件写入内容。

例子 1:

  add-content "c:/new.txt" "Powershell is powerful!"

  将文本"Powershell is powerful!"写入c盘下的new.txt末尾,不会覆盖已存在的内容。如果new.txt不存在,ps自动新建。两个参数的双引号都不是必须的。你可以写为add-content c:/new.txt "Powershell is powerful!", 注意后面"Powershell is powerful!”中间有空格,所以需要双引号包起来作为一个整体传入。

例子 2:

   add-content -path *.txt -exclude help* -value "END"

   将“END” 写入所有当前目录下的txt文件中,以help命名开头的文件除外。

例子 3:

   add-content -path file1.log, file2.log -value (get-date) -passthru

   将当前日期时间写入file1.log,file2.log,同时打印当前日期(-passthru 在无参数的情况下会将值传递给console)

   注意:

    (get-date)一定要用括号括起来,让get-date作为command进行调用,否则get-date会被当成expression计算,最终解释为字符串"get-date".

例子 4:

    add-content -path monthly.txt -value (get-content c:/temp/weekly.txt)

    将weekly.txt的内容添加到monthly.txt的末尾。

例子 5:

    add-content -value (get-content test.log) -path C:/tests/test134/logs/test134.log

    将test.log的内容添加到test134.log文件中去。如果目标文件不存在,自动创建,如果上层目录不存在,自动创建。

例子 6:

    add-content chinese.txt -encoding "UTF8" -value "中文"

    利用"UTF8"编码将多国语言文字写入目标文件中。目前能接受的Encoding参数为

        Unknown,String,Unicode ,Byte,BigEndianUnicode,UTF8,UTF7,Ascii

  

英文帮助文档如下:

NAME
    Add-Content
   
SYNOPSIS
    Adds content to the specified items, such as adding words to a file.
   
   
SYNTAX
    Add-Content [-Credential <PSCredential>] [-Encoding {Unknown | String | Unicode | Byte | BigEndianUnicode | UTF8 | UTF7 | Ascii
    }] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-LiteralPath] <string[]> [-Value] <Obje
    ct[]> [-confirm] [-whatif] [<CommonParameters>]
   
    Add-Content [-Credential <PSCredential>] [-Encoding {Unknown | String | Unicode | Byte | BigEndianUnicode | UTF8 | UTF7 | Ascii
    }] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Path] <string[]> [-Value] <Object[]> [
    -confirm] [-whatif] [<CommonParameters>]
   
   
DETAILED DESCRIPTION
    The Add-Content cmdlet appends content to a specified item or file. You can specify the content by typing the content in the co
    mmand or by specifying an object that contains the content.

PS C:\Users\Administrator> # 增强版 curl 版本检查脚本 >> function Get-CurlVersionInfo { >> # 获取已安装版本 >> $versionOutput = curl --version 2>&1 | Out-String >> $installedMatch = [regex]::Match($versionOutput, 'curl (\d+\.\d+\.\d+)') >> >> if (-not $installedMatch.Success) { >> throw "无法解析已安装的 curl 版本" >> } >> $installedVersion = $installedMatch.Groups[1].Value >> >> # 获取最新版本 >> try { >> $releaseInfo = curl -s -L --connect-timeout 10 --retry 2 https://curl.se/info >> $latestMatch = [regex]::Match($releaseInfo, 'The latest release: curl (\d+\.\d+\.\d+)') >> >> if (-not $latestMatch.Success) { >> Write-Warning "无法从官网解析最新版本,尝试备用方案" >> $changelog = curl -s -L https://curl.se/changes.html >> $latestMatch = [regex]::Match($changelog, 'curl-(\d+_\d+_\d+)') >> if ($latestMatch.Success) { >> $latestVersion = $latestMatch.Groups[1].Value -replace '_', '.' >> } else { >> throw "无法获取最新版本信息" >> } >> } else { >> $latestVersion = $latestMatch.Groups[1].Value >> } >> } catch { >> Write-Warning "获取最新版本失败: $_" >> $latestVersion = $installedVersion >> } >> >> return @{ >> Installed = $installedVersion >> Latest = $latestVersion >> } >> } >> >> $versions = Get-CurlVersionInfo >> >> if ([version]$versions.Installed -lt [version]$versions.Latest) { >> Write-Host "⚠️ 发现新版本: $($versions.Latest) (当前: $($versions.Installed))" -ForegroundColor Yellow >> Write-Host "执行以下命令更新: winget install curl.curl" -ForegroundColor Cyan >> } else { >> Write-Host "✅ 已安装最新版 curl $($versions.Installed)" -ForegroundColor Green >> } >> 警告: 无法从官网解析最新版本,尝试备用方案 警告: 获取最新版本失败: 无法获取最新版本信息 ✅ 已安装最新版 curl 8.15.0 PS C:\Users\Administrator> # CurlTools.psm1 PS C:\Users\Administrator> $script:CurlPath = "E:\curl-8.15.0_4-win64-mingw\bin" PS C:\Users\Administrator> PS C:\Users\Administrator> function Get-CurlVersion { >> # 上述版本检查代码... >> } PS C:\Users\Administrator> PS C:\Users\Administrator> function Set-CurlVersion { >> param( >> [ValidateSet("8.15", "system")] >> [string]$Version = "8.15" >> ) >> >> $pathItems = [System.Collections.ArrayList]@( >> [Environment]::GetEnvironmentVariable("Path", "Machine") -split ';' >> ) >> >> switch ($Version) { >> "8.15" { >> $pathItems.Remove("C:\Windows\System32") | Out-Null >> if (-not $pathItems.Contains($script:CurlPath)) { >> $pathItems.Insert(0, $script:CurlPath) >> } >> } >> "system" { >> $pathItems.Remove($script:CurlPath) | Out-Null >> if (-not $pathItems.Contains("C:\Windows\System32")) { >> $pathItems.Add("C:\Windows\System32") | Out-Null >> } >> } >> } >> >> $newPath = $pathItems -join ';' >> [Environment]::SetEnvironmentVariable("Path", $newPath, "Machine") >> $env:Path = $newPath >> >> Write-Host "已切换到 curl $Version 版本" -ForegroundColor Green >> } PS C:\Users\Administrator> PS C:\Users\Administrator> function Invoke-SecureDownload { >> param( >> [Parameter(Mandatory=$true)] >> [string]$Url, >> >> [Parameter(Mandatory=$true)] >> [string]$ExpectedHash, >> >> [string]$Algorithm = "SHA256", >> >> [string]$OutputPath = (Split-Path -Leaf $Url) >> ) >> >> try { >> & "$script:CurlPath\curl.exe" -L -o $OutputPath $Url >> $actualHash = (Get-FileHash -Path $OutputPath -Algorithm $Algorithm).Hash >> >> if ($actualHash -ne $ExpectedHash) { >> Remove-Item $OutputPath -Force >> throw "文件哈希验证失败! 期望: $ExpectedHash, 实际: $actualHash" >> } >> >> Write-Host "✅ 文件验证成功: $OutputPath" -ForegroundColor Green >> return $OutputPath >> } catch { >> Write-Error "下载失败: $_" >> return $null >> } >> } PS C:\Users\Administrator> PS C:\Users\Administrator> Export-ModuleMember -Function Get-CurlVersion, Set-CurlVersion, Invoke-SecureDownload Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 行:1 字符: 1 + Export-ModuleMember -Function Get-CurlVersion, Set-CurlVersion, Invok ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand PS C:\Users\Administrator> # CurlTools.psm1 >> $script:CurlPath = "E:\curl-8.15.0_4-win64-mingw\bin" >> >> function Get-CurlVersion { >> # 上述版本检查代码... >> } >> >> function Set-CurlVersion { >> param( >> [ValidateSet("8.15", "system")] >> [string]$Version = "8.15" >> ) >> >> $pathItems = [System.Collections.ArrayList]@( >> [Environment]::GetEnvironmentVariable("Path", "Machine") -split ';' >> ) >> >> switch ($Version) { >> "8.15" { >> $pathItems.Remove("C:\Windows\System32") | Out-Null >> if (-not $pathItems.Contains($script:CurlPath)) { >> $pathItems.Insert(0, $script:CurlPath) >> } >> } >> "system" { >> $pathItems.Remove($script:CurlPath) | Out-Null >> if (-not $pathItems.Contains("C:\Windows\System32")) { >> $pathItems.Add("C:\Windows\System32") | Out-Null >> } >> } >> } >> >> $newPath = $pathItems -join ';' >> [Environment]::SetEnvironmentVariable("Path", $newPath, "Machine") >> $env:Path = $newPath >> >> Write-Host "已切换到 curl $Version 版本" -ForegroundColor Green >> } >> >> function Invoke-SecureDownload { >> param( >> [Parameter(Mandatory=$true)] >> [string]$Url, >> >> [Parameter(Mandatory=$true)] >> [string]$ExpectedHash, >> >> [string]$Algorithm = "SHA256", >> >> [string]$OutputPath = (Split-Path -Leaf $Url) >> ) >> >> try { >> & "$script:CurlPath\curl.exe" -L -o $OutputPath $Url >> $actualHash = (Get-FileHash -Path $OutputPath -Algorithm $Algorithm).Hash >> >> if ($actualHash -ne $ExpectedHash) { >> Remove-Item $OutputPath -Force >> throw "文件哈希验证失败! 期望: $ExpectedHash, 实际: $actualHash" >> } >> >> Write-Host "✅ 文件验证成功: $OutputPath" -ForegroundColor Green >> return $OutputPath >> } catch { >> Write-Error "下载失败: $_" >> return $null >> } >> } >> >> Export-ModuleMember -Function Get-CurlVersion, Set-CurlVersion, Invoke-SecureDownload >> Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 行:70 字符: 1 + Export-ModuleMember -Function Get-CurlVersion, Set-CurlVersion, Invok ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand PS C:\Users\Administrator> # 导入模块 >> Import-Module .\CurlTools.psm1 -Force >> >> # 检查更新 >> Get-CurlVersion >> >> # 安全下载示例 >> $fileUrl = "https://github.com/curl/curl/releases/download/curl-8_15_0/curl-8.15.0.zip" >> $expectedHash = "a1b2c3d4e5f6..." # 实际替换为正确哈希 >> Invoke-SecureDownload -Url $fileUrl -ExpectedHash $expectedHash >> >> # 版本切换 >> Set-CurlVersion -Version system # 切回系统curl >> Set-CurlVersion -Version 8.15 # 切回自定义curl >> Import-Module : 未能加载指定的模块“.\CurlTools.psm1”,因为在任何模块目录中都没有找到有效模块文件。 所在位置 行:2 字符: 1 + Import-Module .\CurlTools.psm1 -Force + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (.\CurlTools.psm1:String) [Import-Module], FileNotFoundException + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand Invoke-SecureDownload : 下载失败: 文件哈希验证失败! 期望: a1b2c3d4e5f6..., 实际: B7B1409A8C05C6C464488F8CB38AF2090D39AC 88B5DCC3FEF0E1EFE8103F77E2 所在位置 行:10 字符: 1 + Invoke-SecureDownload -Url $fileUrl -ExpectedHash $expectedHash + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-SecureDownload 已切换到 curl system 版本 已切换到 curl 8.15 版本 PS C:\Users\Administrator>
08-13
PS C:\Users\Administrator\Desktop> # PythonEnvRepair_Ultimate_Fixed.ps1 PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 1. 修复路径获取逻辑 PS C:\Users\Administrator\Desktop> $desktopPath = [Environment]::GetFolderPath("Desktop") PS C:\Users\Administrator\Desktop> if (-not (Test-Path $desktopPath)) { >> $desktopPath = "C:\Temp\PythonDesktop" >> New-Item -ItemType Directory -Path $desktopPath -Force | Out-Null >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 2. 完全修正的诊断函数 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" -ForegroundColor Red >> return >> } >> >> # 修复的Python诊断脚本(使用单引号避免转义问题) >> $diagnosticScript = @" >> import sys >> import os >> import json >> >> desktop_path = r'$desktopPath' >> result = { >> "desktop_path": desktop_path, >> "in_sys_path": desktop_path in sys.path, >> "sys_path": sys.path >> } >> >> print(json.dumps(result)) >> "@ >> >> try { >> $result = & $pythonExe -c $diagnosticScript | ConvertFrom-Json >> >> Write-Host "`n=== 环境诊断报告 ===" -ForegroundColor Green >> Write-Host "桌面路径: $($result.desktop_path)" >> Write-Host "在sys.path中: $($result.in_sys_path)" >> >> if ($result.in_sys_path) { >> Write-Host "✅ 桌面路径已正确添加" -ForegroundColor Green >> } else { >> Write-Host "❌ 桌面路径未添加" -ForegroundColor Red >> Write-Host "运行命令: Repair-PythonEnvironment -PythonPath '$PythonPath'" -ForegroundColor Cyan >> } >> >> return $true >> } catch { >> Write-Host "❌ 诊断执行失败: $_" -ForegroundColor Red >> return $false >> } >> } 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") >> >> $pythonExe = Join-Path $PythonPath "python.exe" >> if (-not (Test-Path $pythonExe)) { >> Write-Host "❌ 错误: 找不到python.exe" -ForegroundColor Red >> return >> } >> >> # 创建必要的目录 >> $sitePackages = Join-Path $PythonPath "Lib\site-packages" >> if (-not (Test-Path $sitePackages)) { >> New-Item -ItemType Directory -Path $sitePackages -Force | Out-Null >> } >> >> # 1. 创建.pth文件(最可靠的方法) >> $pthPath = Join-Path $sitePackages "desktop_path.pth" >> $desktopPath | Out-File -FilePath $pthPath -Encoding utf8 >> >> # 2. 创建sitecustomize.py(增强版) >> $sitecustomizeContent = @" >> import sys >> import os >> import site >> >> # 添加桌面路径 >> desktop_path = r'$desktopPath' >> if desktop_path not in sys.path: >> sys.path.insert(0, desktop_path) >> >> # 添加.pth文件支持 >> site.addsitedir(r'$sitePackages') >> "@ >> $sitecustomizePath = Join-Path $sitePackages "sitecustomize.py" >> $sitecustomizeContent | Out-File -FilePath $sitecustomizePath -Encoding utf8 >> >> # 3. 设置环境变量 >> [Environment]::SetEnvironmentVariable("PYTHONPATH", $desktopPath, "Machine") >> >> 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-PythonPath { >> param([string]$PythonPath = "E:\Python310") >> >> $pythonExe = Join-Path $PythonPath "python.exe" >> if (-not (Test-Path $pythonExe)) { >> Write-Host "❌ 错误: 找不到python.exe" -ForegroundColor Red >> return >> } >> >> # 修复验证命令(使用单引号) >> $checkCommand = @" >> import sys >> desktop_path = r'$desktopPath' >> print('✅ 桌面路径在sys.path中' if desktop_path in sys.path else '❌ 路径未添加') >> "@ >> >> & $pythonExe -c $checkCommand >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 5. 主执行逻辑 PS C:\Users\Administrator\Desktop> param([string]$PythonPath = "E:\Python310") PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 执行修复 PS C:\Users\Administrator\Desktop> Repair-PythonEnvironment -PythonPath $PythonPath ✅ Python环境修复完成 True PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 验证修复 PS C:\Users\Administrator\Desktop> Write-Host "`n验证修复结果:" -ForegroundColor Cyan 验证修复结果: PS C:\Users\Administrator\Desktop> Test-PythonEnvironment -PythonPath $PythonPath Traceback (most recent call last): File "<string>", line 8, in <module> NameError: name 'in_sys_path' is not defined === 环境诊断报告 === 桌面路径: 在sys.path中: ❌ 桌面路径未添加 运行命令: Repair-PythonEnvironment -PythonPath 'E:\Python310' True PS C:\Users\Administrator\Desktop> Test-PythonPath -PythonPath $PythonPath ✅ 桌面路径在sys.path中 PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 6. 清理函数 PS C:\Users\Administrator\Desktop> function global:Clean-PythonFiles { >> # 清理旧脚本 >> $locations = @( >> [Environment]::GetFolderPath("Desktop"), >> [Environment]::GetFolderPath("MyDocuments"), >> "C:\Temp", >> $env:USERPROFILE >> ) >> >> $patterns = @("*PythonEnvRepair*.ps1", "*PythonFix*") >> >> foreach ($location in $locations) { >> if (Test-Path $location) { >> foreach ($pattern in $patterns) { >> Get-ChildItem -Path $location -Filter $pattern -Recurse -ErrorAction SilentlyContinue | Remove-Item -Force >> } >> } >> } >> >> Write-Host "✅ 清理完成" -ForegroundColor Green >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 7. 保存脚本到安全位置 PS C:\Users\Administrator\Desktop> $scriptDir = "C:\PythonTools" PS C:\Users\Administrator\Desktop> if (-not (Test-Path $scriptDir)) { >> New-Item -ItemType Directory -Path $scriptDir -Force | Out-Null >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> $scriptPath = Join-Path $scriptDir "PythonEnvRepair_Ultimate_Fixed.ps1" PS C:\Users\Administrator\Desktop> $MyInvocation.MyCommand.Definition | Out-File -FilePath $scriptPath -Encoding utf8 PS C:\Users\Administrator\Desktop> Write-Host "主脚本位置: $scriptPath" -ForegroundColor Cyan 主脚本位置: C:\PythonTools\PythonEnvRepair_Ultimate_Fixed.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 "修复环境: Repair-PythonEnvironment -PythonPath '$PythonPath'" -ForegroundColor Cyan 修复环境: Repair-PythonEnvironment -PythonPath 'E:\Python310' PS C:\Users\Administrator\Desktop> Write-Host "诊断环境: Test-PythonEnvironment -PythonPath '$PythonPath'" -ForegroundColor Cyan 诊断环境: Test-PythonEnvironment -PythonPath 'E:\Python310' PS C:\Users\Administrator\Desktop> Write-Host "清理文件: Clean-PythonFiles" -ForegroundColor Yellow 清理文件: Clean-PythonFiles PS C:\Users\Administrator\Desktop> Test-PythonEnvironment -PythonPath "E:\Python310" Traceback (most recent call last): File "<string>", line 8, in <module> NameError: name 'in_sys_path' is not defined === 环境诊断报告 === 桌面路径: 在sys.path中: ❌ 桌面路径未添加 运行命令: Repair-PythonEnvironment -PythonPath 'E:\Python310' True PS C:\Users\Administrator\Desktop> Test-PythonPath -PythonPath "E:\Python310" ✅ 桌面路径在sys.path中 PS C:\Users\Administrator\Desktop> # 启动Python交互式环境 PS C:\Users\Administrator\Desktop> & "E:\Python310\python.exe" Python 3.10.10 (tags/v3.10.10:aad5f6a, Feb 7 2023, 17:20:36) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> # 从桌面运行(仅需一次) >>> .\PythonEnvRepair_Ultimate_Fixed.ps1 -PythonPath "E:\Python310" File "<stdin>", line 1 .\PythonEnvRepair_Ultimate_Fixed.ps1 -PythonPath "E:\Python310" ^ SyntaxError: invalid syntax >>> # 修复环境 >>> Repair-PythonEnvironment -PythonPath "E:\Python310" File "<stdin>", line 1 Repair-PythonEnvironment -PythonPath "E:\Python310" ^^^^^^^^^^^^^^ SyntaxError: invalid syntax >>> >>> # 诊断环境 >>> Test-PythonEnvironment -PythonPath "E:\Python310" File "<stdin>", line 1 Test-PythonEnvironment -PythonPath "E:\Python310" ^^^^^^^^^^^^^^ SyntaxError: invalid syntax >>> >>> # 清理旧文件 >>> Clean-PythonFiles Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'Clean' is not defined >>> function Add-PythonPath { File "<stdin>", line 1 function Add-PythonPath { ^^^ SyntaxError: invalid syntax >>> param([string]$Path) File "<stdin>", line 1 param([string]$Path) IndentationError: unexpected indent >>> >>> # 1. 添加到PYTHONPATH >>> $currentPath = [Environment]::GetEnvironmentVariable("PYTHONPATH", "Machine") File "<stdin>", line 1 $currentPath = [Environment]::GetEnvironmentVariable("PYTHONPATH", "Machine") IndentationError: unexpected indent >>> $newPath = if ($currentPath) { "$currentPath;$Path" } else { $Path } File "<stdin>", line 1 $newPath = if ($currentPath) { "$currentPath;$Path" } else { $Path } IndentationError: unexpected indent >>> [Environment]::SetEnvironmentVariable("PYTHONPATH", $newPath, "Machine") File "<stdin>", line 1 [Environment]::SetEnvironmentVariable("PYTHONPATH", $newPath, "Machine") IndentationError: unexpected indent >>> >>> # 2. 创建新的.pth文件 >>> $pthPath = Join-Path "E:\Python310\Lib\site-packages" "$(Get-Date -Format 'yyyyMMdd_HHmmss').pth" File "<stdin>", line 1 $pthPath = Join-Path "E:\Python310\Lib\site-packages" "$(Get-Date -Format 'yyyyMMdd_HHmmss').pth" IndentationError: unexpected indent >>> $Path | Out-File -FilePath $pthPath -Encoding utf8 File "<stdin>", line 1 $Path | Out-File -FilePath $pthPath -Encoding utf8 IndentationError: unexpected indent >>> >>> Write-Host "✅ 路径已添加: $Path" -ForegroundColor Green File "<stdin>", line 1 Write-Host "✅ 路径已添加: $Path" -ForegroundColor Green IndentationError: unexpected indent >>> } File "<stdin>", line 1 } ^ SyntaxError: unmatched '}' >>> >>> # 示例:添加新路径 >>> Add-PythonPath -Path "D:\MyProject\src" File "<stdin>", line 1 Add-PythonPath -Path "D:\MyProject\src" ^^^^^^^^^^^^^^^^^^ SyntaxError: invalid syntax >>> # 创建虚拟环境 >>> python -m venv myenv File "<stdin>", line 1 python -m venv myenv ^^^^ SyntaxError: invalid syntax >>> >>> # 激活虚拟环境 >>> .\myenv\Scripts\activate.ps1 File "<stdin>", line 1 .\myenv\Scripts\activate.ps1 ^ SyntaxError: invalid syntax >>> # 在激活脚本中添加路径 >>> Add-Content -Path ".\myenv\Scripts\activate.ps1" -Value @" File "<stdin>", line 1 Add-Content -Path ".\myenv\Scripts\activate.ps1" -Value @" ^ SyntaxError: unterminated string literal (detected at line 1) >>> `$env:PYTHONPATH = `"`$env:PYTHONPATH;C:\MyProject`" File "<stdin>", line 1 `$env:PYTHONPATH = `"`$env:PYTHONPATH;C:\MyProject`" ^ SyntaxError: invalid syntax >>> "@ File "<stdin>", line 1 "@ ^ SyntaxError: unterminated string literal (detected at line 1) >>> >>> # 在项目目录中创建setup.py >>> @" File "<stdin>", line 1 @" ^ SyntaxError: unterminated string literal (detected at line 1) >>> from setuptools import setup >>> setup(name='myproject', version='1.0', packages=['']) WARNING: '' not a valid package name; please use only .-separated package names in setup.py usage: [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: --help [cmd1 cmd2 ...] or: --help-commands or: cmd --help error: no commands supplied PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 在Python中执行 PS C:\Users\Administrator\Desktop> >>> import sys >> : 无法将“>>”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 1 + >>> import sys + ~~ + CategoryInfo : ObjectNotFound: (>>:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> >>> r'C:\Users\Administrator\Desktop' in sys.path >> : 无法将“>>”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 1 + >>> r'C:\Users\Administrator\Desktop' in sys.path + ~~ + CategoryInfo : ObjectNotFound: (>>:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> True True : 无法将“True”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 1 + True + ~~~~ + CategoryInfo : ObjectNotFound: (True:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> "@ | Out-File -FilePath "setup.py" -Encoding utf8 >> >> # 以可编辑模式安装 >> pip install -e . >>
最新发布
08-24
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>
08-23
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值