0
0

Windows で Python embeddable のインストールディレクトリを力業で移動させる

Last updated at Posted at 2024-08-14

Python embeddable のセットアップ

はじめに

諸々の事情があって、Python embeddable でも pip を使用できるようにインストールしている方がいらっしゃると思います。ただこれは問題があって、折角 pip が使えるのにディレクトリを移動させるとうまく動かないことがあるので、無理やり移動先でも動かそうという試みです。

原因

もともとのインストールディレクトリが D:\Work\debug\python だったとして、D:\Work\debug\python2 にリネームした場合、Scripts 以下のファイルに絶対パスが仕込まれていて、参照先が見つけられないのが原因です。

D:\Work\debug\python2>pip
Fatal error in launcher: Unable to create process using '"D:\Work\debug\python\python.exe"  "D:\Work\debug\python2\Scripts\pip.exe" ': ?????????????

D:\Work\debug\python2>

SnapCrab_Quick Be - DWorkdebugpythonScriptspipexe_2024-8-14_23-37-38_No-00.png

厄介なのがリネームではなく単にコピーした場合、元ファイルが残っているので一見挙動が普通で、気が付きにくい事です。私は別PCで動かそうとした場合、あれ?となりました。さらに pip に限らず、Scripts 以下の exe ファイルなのでいやらしい。

対処法

パスを無理やり書き換えます(ぉ。複数のファイルを見ると、0x1A602番地から始まっているようです。今回は決め打ちで書き換えますが、Python のバージョンによると思うので、3.12.5 ではない場合は変わっている可能性があります。あまり検証していないので、自己責任でお願いします。

rewrite_path.py
import os

def modify_file(file_path):
    begin = 0x1A602

    with open(file_path, 'r+b') as file:
        file.seek(begin)
        data = file.read()
        
        end = data.find(b'python.exe')
        if end == -1:
            return
        
        file.seek(begin)
        for i in range(0, end):
            file.write(b'\x20')

def rewrite_exe_files(directory):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.exe'):
                modify_file(os.path.join(root, file))
    return

rewrite_exe_files('.\\Scripts')

使い方

エラーが出たときに、rewrite_path.py を実行します。書き換え後は絶対パスではなく python.exe だけになりますので、python.exe にパスが通っている必要があります。

参考にしたサイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0