メインコンテンツへスキップ
見出し画像

How to update embedded Python on ComfyUI

    以前、グローバル環境Pythonのtarファイルからの更新については、以下記事にて解説していますが、

    今回は、ComyUI Portable版のEmbeded python環境を更新する方法について、ps1形式で自動スクリプト化したので、公開します。

    当然、以下のパスは私の環境です。

    # ComfyUI Embedded Python Update Script
    # Usage: .\update_python_embeded.ps1 -SourcePath "D:\python-3.13.9-embed-amd64"
    
    param(
        [Parameter(Mandatory=$false)]
        [string]$SourcePath = "",
        
        [Parameter(Mandatory=$false)]
        [string]$ComfyUIPath = "D:\USERFILES\ComfyUI"
    )
    
    $ErrorActionPreference = "Stop"
    
    Write-Host "=== ComfyUI Embedded Python Update Script ===" -ForegroundColor Cyan
    
    # If source path is not specified, search D drive
    if ([string]::IsNullOrEmpty($SourcePath)) {
        Write-Host "Searching for embedded Python on D drive..." -ForegroundColor Yellow
        $pythonDirs = Get-ChildItem -Path "D:\" -Directory -Filter "python-*-embed-amd64" -ErrorAction SilentlyContinue
        
        if ($pythonDirs.Count -eq 0) {
            Write-Host "ERROR: No embedded Python found on D drive" -ForegroundColor Red
            Write-Host "Usage: .\update_python_embeded.ps1 -SourcePath `"D:\python-3.13.9-embed-amd64`"" -ForegroundColor Yellow
            exit 1
        }
        
        if ($pythonDirs.Count -eq 1) {
            $SourcePath = $pythonDirs[0].FullName
            Write-Host "Detected: $SourcePath" -ForegroundColor Green
        } else {
            Write-Host "Multiple embedded Python installations found:" -ForegroundColor Yellow
            for ($i = 0; $i -lt $pythonDirs.Count; $i++) {
                Write-Host "  [$i] $($pythonDirs[$i].Name)" -ForegroundColor White
            }
            $selection = Read-Host "Select number (0-$($pythonDirs.Count-1))"
            $SourcePath = $pythonDirs[[int]$selection].FullName
        }
    }
    
    # Validate paths
    if (-not (Test-Path $SourcePath)) {
        Write-Host "ERROR: Source path does not exist: $SourcePath" -ForegroundColor Red
        exit 1
    }
    
    $TargetPath = Join-Path $ComfyUIPath "python_embeded"
    if (-not (Test-Path $TargetPath)) {
        Write-Host "ERROR: Target path does not exist: $TargetPath" -ForegroundColor Red
        exit 1
    }
    
    Write-Host "`n=== Update Information ===" -ForegroundColor Cyan
    Write-Host "Source: $SourcePath" -ForegroundColor White
    Write-Host "Target: $TargetPath" -ForegroundColor White
    
    # Confirmation
    $confirm = Read-Host "`nContinue? (y/n)"
    if ($confirm -ne "y") {
        Write-Host "Cancelled" -ForegroundColor Yellow
        exit 0
    }
    
    Write-Host "`n=== Step 1: Copying Files ===" -ForegroundColor Cyan
    
    # Detect python3xx._pth filename
    $pthFile = Get-ChildItem -Path $SourcePath -Filter "python*._pth" | Select-Object -First 1
    if (-not $pthFile) {
        Write-Host "ERROR: ._pth file not found" -ForegroundColor Red
        exit 1
    }
    $pthFileName = $pthFile.Name
    Write-Host "Detected ._pth file: $pthFileName" -ForegroundColor Green
    
    # Copy all files
    Write-Host "Copying files..." -ForegroundColor Yellow
    $files = Get-ChildItem -Path $SourcePath -File
    $totalFiles = $files.Count
    $currentFile = 0
    
    foreach ($file in $files) {
        $currentFile++
        Write-Progress -Activity "Copying files" -Status "$currentFile / $totalFiles" -PercentComplete (($currentFile / $totalFiles) * 100)
        Copy-Item -Path $file.FullName -Destination $TargetPath -Force
    }
    Write-Progress -Activity "Copying files" -Completed
    Write-Host "✓ Copied $totalFiles files" -ForegroundColor Green
    
    Write-Host "`n=== Step 2: Editing $pthFileName ===" -ForegroundColor Cyan
    
    $pthTargetPath = Join-Path $TargetPath $pthFileName
    
    # Read current content
    $currentContent = Get-Content -Path $pthTargetPath -Raw
    Write-Host "Current content:" -ForegroundColor Yellow
    Write-Host $currentContent -ForegroundColor Gray
    
    # Extract Python version number (e.g., python313.zip -> 313)
    $zipFile = Get-ChildItem -Path $TargetPath -Filter "python*.zip" | Select-Object -First 1
    $zipFileName = $zipFile.Name
    
    # Create new content as array of lines
    $newContent = @(
        $zipFileName,
        ".",
        "..",
        "..\ComfyUI",
        "Lib",
        "Lib\site-packages",
        "",
        "# Uncomment to run site.main() automatically",
        "import site",
        ""
    )
    
    # Write file with CRLF line endings and final newline
    $newContent -join "`r`n" | Set-Content -Path $pthTargetPath -NoNewline -Encoding ASCII
    Write-Host "✓ Updated $pthFileName" -ForegroundColor Green
    
    Write-Host "`nNew content:" -ForegroundColor Yellow
    Write-Host $newContent -ForegroundColor Gray
    
    Write-Host "`n=== Step 3: Verification ===" -ForegroundColor Cyan
    
    $pythonExe = Join-Path $TargetPath "python.exe"
    Write-Host "Checking Python version..." -ForegroundColor Yellow
    
    $version = & $pythonExe --version 2>&1
    Write-Host "✓ $version" -ForegroundColor Green
    
    Write-Host "`nChecking Python paths..." -ForegroundColor Yellow
    $pythonPaths = & $pythonExe -c "import sys; print('\n'.join(sys.path))" 2>&1
    Write-Host $pythonPaths -ForegroundColor Gray
    
    Write-Host "`n=== Complete ===" -ForegroundColor Green
    Write-Host "Embedded Python update completed successfully" -ForegroundColor Green
    Write-Host "Please launch ComfyUI to verify operation" -ForegroundColor Yellow
    

    想定としては、ダウンロードしたEmbedded PythonフォルダをDドライブ直下に置く事で、D:\USERFILES\ComfyUI内のEmbedded Pythonが、ライブラリーは維持したまま、更新される仕組みです。

    ライブラリー維持という事は、マイナーバージョンアップにのみ有効であり、3.12→3.13のようなメジャーバージョンアップには対応しません。

    これにより、以下の様にインストール時は3.13.6だったPythonが、3.13.9に更新されました。

    画像

    ComfyUI 埋め込み型Python更新 完全ガイド

    概要

    ComfyUIの埋め込み型Python(`python_embeded`)を新しいバージョンに更新する際、単純にファイルをコピーするだけでは起動しません。`python3xx._pth`ファイルの設定が重要です。

    問題の本質

    なぜ単純コピーでは動かないのか

    埋め込み型Pythonには`python313._pth`というファイルがあり、これがPythonのモジュール検索パス(`sys.path`)を完全に制御します。

    デフォルトの`python313._pth`(ダウンロード版):

    python313.zip
    .
    
    # Uncomment to run site.main() automatically
    #import site

    この状態では:

    • `python313.zip` - 標準ライブラリ(圧縮版)のみ

    • `.` - カレントディレクトリのみ

    不足しているもの:

    • `..` と `..\ComfyUI` - ComfyUI本体へのパス

    • `Lib` と `Lib\site-packages` - インストール済みパッケージへのパス

    • `import site` - site-packagesの初期化

    正しい`python313._pth`の内容

    python313.zip
    .
    ..
    ..\ComfyUI
    Lib
    Lib\site-packages
    
    # Uncomment to run site.main() automatically
    import site
    

    重要:最後に空行が必要

    ファイル作成の落とし穴

    問題1: 文字エンコーディング

    NG: UTF-8 BOM付き、UTF-8

    Set-Content -Path $file -Value $content -Encoding UTF8

    → Pythonが正しく読み込めない

    OK: ASCII

    Set-Content -Path $file -Value $content -Encoding ASCII

    問題2: 改行コード

    NG: LF(`\n`)のみ

    $content | Out-File -FilePath $file -Encoding utf8

    → Windowsでは問題が発生する可能性

    OK: CRLF(`\r\n`)

    $content -join "`r`n" | Set-Content -Path $file -NoNewline -Encoding ASCII

    問題3: 最後の改行

    重要:最後に必ず改行が必要

    $newContent = @(
        "python313.zip",
        ".",
        "..",
        "..\ComfyUI",
        "Lib",
        "Lib\site-packages",
        "",
        "# Uncomment to run site.main() automatically",
        "import site",
        ""  # ← これが重要!
    )
    
    $newContent -join "`r`n" | Set-Content -Path $file -NoNewline -Encoding ASCII

    最後の空文字列(`""`)を配列に含めることで、最後の行(`import site`)の後に改行が入ります。

    自動化スクリプト

    配置場所

    D:\update_python_embeded.ps1

    使い方

    # 基本的な使い方(自動検出)
    cd D:\
    .\update_python_embeded.ps1
    
    # パスを明示的に指定
    .\update_python_embeded.ps1 -SourcePath "D:\python-3.13.9-embed-amd64"
    
    # ComfyUIのパスも指定
    .\update_python_embeded.ps1 -SourcePath "D:\python-3.13.9-embed-amd64" -ComfyUIPath "D:\USERFILES\ComfyUI"

    スクリプトの動作

    1. ソース検出

      • Dドライブから`python-*-embed-amd64`を検索

      • 複数ある場合は選択

    2. ファイルコピー

      • 全34個のファイルを上書きコピー

      • `python.exe`, `python313.dll`, `python313.zip`, `.pyd`, `.dll`など

    3. `._pth`ファイル編集

      • 自動的にバージョンに対応(`python313._pth`, `python314._pth`等)

      • ASCII encoding、CRLF改行、最後の改行を確保

      • 必要なパスを追加

    4. 動作確認

      • Pythonバージョン表示

      • `sys.path`の確認

    トラブルシューティング

    エラー: Fatal Python error: Failed to import encodings module

    原因: `python313._pth`の内容が正しくない

    確認コマンド:

    Get-Content "D:\USERFILES\ComfyUI\python_embeded\python313._pth" -Raw | Format-Hex

    期待される出力:

    • CRLF改行コード(`0D 0A`)が各行の後にある

    • ASCIIエンコーディング(特殊文字なし)

    • 最後に`0D 0A`で終わる

    修正方法:

    # 手動で修正
    $content = @("python313.zip", ".", "..", "..\ComfyUI", "Lib", "Lib\site-packages", "", "# Uncomment to run site.main() automatically", "import site", "")
    $content -join "`r`n" | Set-Content "D:\USERFILES\ComfyUI\python_embeded\python313._pth" -NoNewline -Encoding ASCII

    エラー: ModuleNotFoundError: No module named 'comfy'

    原因: `sys.path`に`ComfyUI`ディレクトリが含まれていない

    確認コマンド:

    D:\USERFILES\ComfyUI\python_embeded\python.exe -c "import sys; [print(p) for p in sys.path]"

    期待される出力に含まれるべきもの:

    • `D:\USERFILES\ComfyUI\ComfyUI`

    • `D:\USERFILES\ComfyUI\python_embeded\Lib\site-packages`

    修正: `._pth`ファイルに`..`と`..\ComfyUI`が含まれているか確認

    動作確認コマンド集

    # Pythonバージョン確認
    D:\USERFILES\ComfyUI\python_embeded\python.exe --version
    
    # 基本動作確認
    D:\USERFILES\ComfyUI\python_embeded\python.exe -c "print('OK')"
    
    # sys.path確認
    D:\USERFILES\ComfyUI\python_embeded\python.exe -c "import sys; [print(p) for p in sys.path]"
    
    # torchが読み込めるか確認
    D:\USERFILES\ComfyUI\python_embeded\python.exe -c "import torch; print(torch.__version__)"
    
    # comfyモジュールが読み込めるか確認
    cd D:\USERFILES\ComfyUI\ComfyUI
    ..\python_embeded\python.exe -c "import comfy; print(comfy.__file__)"
    
    # ComfyUIが起動するか確認
    cd D:\USERFILES\ComfyUI\ComfyUI
    ..\python_embeded\python.exe main.py --help

    まとめ

    手動更新の手順

    1. 新しい埋め込み型Pythonの全ファイルをコピー

    2. `python313._pth`を以下の内容で作成:

    $content = @("python313.zip", ".", "..", "..\ComfyUI", "Lib", "Lib\site-packages", "", "# Uncomment to run site.main() automatically", "import site", "")
    $content -join "`r`n" | Set-Content "D:\USERFILES\ComfyUI\python_embeded\python313._pth" -NoNewline -Encoding ASCII

    自動更新の手順

    cd D:\
    .\update_python_embeded.ps1

    重要ポイント

    1. `._pth`ファイルは必ず編集が必要

    2. ASCII encoding、CRLF改行、最後の改行を確保

    3. `..\ComfyUI`と`Lib\site-packages`を必ず追加

    4. `import site`のコメントを外す

    次回Python 3.13.xを更新する際も、同じスクリプトが使えます。

     
     

    GJL

     
     
    Road bike&Cycling Road Race, Respecting Mr.Greg LeMond, & Anti Doping, Football, Rock&Pops, History.

    あなたへのおすすめ