本日はBlenderPython枠です。
〇BlenderのPythonパスの指定
前回はBlenderがインストールされているパスを取得することはできましたが、実際はBlenderのPythonに対してライブラリをインストールする必要があります。
そこで前回の方法と、Blenderのバージョンを取得する方法を組み合わせてBlenderのPythonパスを取得します。
次のコードでパスを取得できます。
# Blenderの実行ファイルパスを取得 blender_exec_path = bpy.app.binary_path blender_version = bpy.app.version major_version = str(blender_version[0]) # 整数を文字列に変換 minor_version = str(blender_version[1]) # 整数を文字列に変換 python_path = blender_exec_path + '\\' + major_version + '.' + minor_version + '\\python'
〇ライブラリが存在しない場合バッチファイルを実行する処理
ライブラリがBlenderにインストールされていない場合バッチファイルにPythonのパスを書き込み実行するコマンドは以下になります。
import bpy import os import re import subprocess def check_library(): # Blenderに組み込まれたMessagePackライブラリを使用してみる try: import msgpack return True except ImportError: return False # Blenderの実行ファイルパスを取得 blender_exec_path = bpy.app.binary_path blender_version = bpy.app.version major_version = str(blender_version[0]) # 整数を文字列に変換 minor_version = str(blender_version[1]) # 整数を文字列に変換 # Blenderのインストールディレクトリを取得 blender_install_dir = os.path.dirname(blender_exec_path) python_path = blender_install_dir + '\\' + major_version + '.' + minor_version + '\\python' #batファイルパスを定義(この例ではDドライブ直下に配置) file_path = os.path.join(os.path.expanduser("~"), 'D:', 'test.bat') with open(file_path, 'r') as f: content = f.read() print("読み込んだテキスト: ", content)#Debug # <>で囲まれた部分を見つける pattern = r'<(.*?)>' matches = re.findall(pattern, content) # 見つけた部分を書き換える new_content = content for match in matches: new_content = new_content.replace('<' + match + '>', python_path) # Blenderのインストールパスをファイルに書き込みます with open(file_path, 'w') as f: f.write(new_content) print("書き込んだテキスト: ", new_content) result = check_library() result = check_library() if result: print("MessagePackライブラリがBlenderに組み込まれています。") else: print("MessagePackライブラリがBlenderに組み込まれていません。") # subprocessを使用して.batファイルを実行します。 subprocess.call(file_path)
次にバッチファイルの中身です。 バッチファイルではpipコマンドを使用します。
@echo off set PYTHON_PATH=C:\Blender\stable\blender-3.5.0-windows-x64\3.5\python start explorer %PYTHON_PATH% pip install msgpack
以上を実行するともしライブラリが導入されていない場合実行しているBlenderのPython環境にライブラリがインストールされるようになりました。