Hi
TLDR summary - I can’t install python modules after updating Unity Hub to 3.11.1 - please help!
I’ve been using python within the Unity Editor to run scripts successfully until a recent Unity Hub upgrade to 3.11.1
The issue I’m getting is it seems I can no longer use the following code to install python modules.
public static void TestAPI()
{
string pythonCode = @"
import sys
class UnityLogger:
def write(self, message):
if message.strip(): # Avoid empty lines
import clr # Needed for Unity compatibility
from UnityEngine import Debug
Debug.Log(message)
def flush(self):
pass # No need to implement flush for Unity logger
sys.stdout = UnityLogger()
sys.stderr = UnityLogger()
print('Python executable path: ' + sys.executable)
print('Python version: ' + sys.version)
import importlib.util
import subprocess
def install_and_import(package):
if importlib.util.find_spec(package) is None:
print(f'{package} not found. Installing...')
subprocess.run([sys.executable, '-m', 'pip', 'install', package], check=True)
else:
print(f'{package} is already installed.')
# Example: Ensure OpenAI is installed
install_and_import('openai')
import openai
print('OpenAI library successfully imported')
";
PythonRunner.RunString(pythonCode);
}
I am now triggering an error when trying to import the module, in this case openai. It says module not found (and it also doesn’t find it during the install process). This also doesn’t work for other modules
This has not been working since the update to 3.11.1 (or perhaps before - I’ve not tracked when this updated)
FYI to be able to run this code at all, I start Unity Hub via terminal (macOS) as follows (this allows environmental variable access for api key amongst else):
open -a "Unity Hub" --args -p "my/path/to/repo/" -v 2022.3.46f1
When I try and run the python code above in editor, it now first switches focus to the Unity Hub and seemingly tries to load something. It didn’t do this before.
I can still import the environmental variables, so i think the terminal part is still ok - I’m thinking maybe the subprocess install is now prevented somehow? Was this done in the recent updates?
At the end of the day I just want to run python with custom modules in unity, calling environmental variables for api keys - so if there is a better way to do this please let me know!
Thanks in advance!
best, Rob