import os
import sys
import multiprocessing
from .logging_config import get_logger
logger = get_logger(__name__)
_configured = False
def find_python_executable():
if sys.executable.endswith("foldit-worker"):
env_dir = os.path.dirname(os.path.dirname(sys.executable))
possible_paths = [
os.path.join(os.path.dirname(sys.executable), "python"),
os.path.join(os.path.dirname(sys.executable), "python3"),
os.path.join(env_dir, ".pixi", "envs", "foundry", "bin", "python"),
os.path.join(env_dir, ".pixi", "envs", "foundry-cpu", "bin", "python"),
]
if hasattr(sys, "base_executable") and sys.base_executable:
possible_paths.append(sys.base_executable)
possible_paths.append("python3")
for path in possible_paths:
if os.path.exists(path):
return path
logger.warning(
"Could not find Python interpreter, keeping sys.executable as %s",
sys.executable,
)
return None
if "PYTHONHOME" in os.environ:
python_exe = os.path.join(os.environ["PYTHONHOME"], "bin", "python")
if os.path.exists(python_exe):
return python_exe
else:
logger.warning("Python executable not found at %s", python_exe)
return None
logger.debug("PYTHONHOME not set, sys.executable is %s", sys.executable)
return None
def configure_multiprocessing():
global _configured
if _configured:
return
python_path = find_python_executable()
if python_path:
sys.executable = python_path
logger.info("Set sys.executable to %s", python_path)
try:
multiprocessing.set_start_method("spawn", force=True)
logger.debug("multiprocessing start method set to 'spawn'")
except RuntimeError:
logger.debug(
"multiprocessing start method already set: %s",
multiprocessing.get_start_method(),
)
if hasattr(multiprocessing, "set_executable"):
multiprocessing.set_executable(sys.executable)
logger.debug("multiprocessing executable set to %s", sys.executable)
_configured = True