diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 94af855..a878fed 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -59,6 +59,98 @@ jobs: env: PYTHON: python + # The runner image registers the Pythons in its tool cache under + # Software\Python\PythonCore. The newest one is found, which may not have + # numpy, so only standard libraries are imported. + - name: Find Python in the registry + shell: pwsh + run: | + # Hide every python.exe on PATH, so that PyCall has to find Python by itself. + $env:PATH = ($env:PATH -split ';' | Where-Object { + $_ -and -not (Test-Path (Join-Path $_ python.exe)) -and -not (Test-Path (Join-Path $_ python3.exe)) + }) -join ';' + if (Get-Command python, python3 -ErrorAction SilentlyContinue) { throw 'Python is still on PATH' } + Remove-Item Env:PYTHON -ErrorAction SilentlyContinue + @' + require 'pycall' + puts PyCall.sys.prefix + # These load DLLs that are next to python3XX.dll. + %w[ctypes ssl sqlite3].each {|name| PyCall.import_module(name) } + '@ | ruby -Ilib -Iext/pycall + if ($LASTEXITCODE) { exit $LASTEXITCODE } + env: + PYCALL_DEBUG_FIND_LIBPYTHON: 1 + + # Miniforge installed with /RegisterPython=1 registers itself under + # Software\Python\PythonCore. PyCall has to find it there when it is the + # only Python registered and nothing is on PATH. + registry: + name: registry:miniforge/ruby-${{ matrix.ruby }} + runs-on: windows-latest + + strategy: + fail-fast: false + matrix: + ruby: + - "3.3" + + defaults: + run: + shell: pwsh + + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 1 + + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + + - run: bundle install + + - run: rake compile + + - name: Install Miniforge registered as the system Python + run: | + # Remove the registrations of the runner image, so that only Miniforge is registered. + Remove-Item -Recurse -Force HKLM:\SOFTWARE\Python, HKLM:\SOFTWARE\WOW6432Node\Python, HKCU:\Software\Python -ErrorAction SilentlyContinue + $installer = Join-Path $env:RUNNER_TEMP miniforge.exe + $prefix = Join-Path $env:RUNNER_TEMP miniforge3 + Invoke-WebRequest https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-Windows-x86_64.exe -OutFile $installer + Start-Process -Wait -FilePath $installer -ArgumentList '/S', '/InstallationType=JustMe', '/RegisterPython=1', '/AddToPath=0', "/D=$prefix" + & (Join-Path $prefix python.exe) -m pip install numpy + if ($LASTEXITCODE) { exit $LASTEXITCODE } + reg query HKCU\Software\Python /s + "EXPECTED_PYTHON_PREFIX=$prefix" >> $env:GITHUB_ENV + + - name: Find Python in the registry + run: | + # Hide every python.exe on PATH, so that PyCall has to find Python by itself. + $env:PATH = ($env:PATH -split ';' | Where-Object { + $_ -and -not (Test-Path (Join-Path $_ python.exe)) -and -not (Test-Path (Join-Path $_ python3.exe)) + }) -join ';' + if (Get-Command python, python3 -ErrorAction SilentlyContinue) { throw 'Python is still on PATH' } + Remove-Item Env:PYTHON -ErrorAction SilentlyContinue + @' + require 'pycall' + prefix = PyCall.sys.prefix + puts prefix + expected = ENV.fetch('EXPECTED_PYTHON_PREFIX') + abort "Expected Python in #{expected}, but used #{prefix}" unless File.identical?(prefix, expected) + # These load DLLs that are next to python3XX.dll, or in Library\bin of conda. + %w[ctypes ssl sqlite3 numpy].each {|name| PyCall.import_module(name) } + '@ | ruby -Ilib -Iext/pycall + if ($LASTEXITCODE) { exit $LASTEXITCODE } + + # No other job runs the suites with the Python found by PyCall itself. + # finder_spec.rb runs python on PATH. + ruby -Iext/pycall -S rspec --exclude-pattern spec/pycall/libpython/finder_spec.rb + if ($LASTEXITCODE) { exit $LASTEXITCODE } + ruby test/run-test.rb + env: + PYCALL_DEBUG_FIND_LIBPYTHON: 1 + conda: name: conda:ruby-${{ matrix. ruby }}/python-${{ matrix.python }} runs-on: windows-latest @@ -81,34 +173,34 @@ jobs: with: fetch-depth: 1 + - uses: ruby/setup-ruby@v1 + if: matrix.ruby_version != 'master-nightly' + with: + ruby-version: ${{ matrix.ruby }} + + # Build before conda is activated, and do not build after that. The + # activated environment comes first in PATH, and the compiler of MSYS2 + # fails there with conda-forge packages. + - run: bundle install + + - run: rake compile + - uses: conda-incubator/setup-miniconda@v4 with: + miniforge-version: latest activate-environment: test python-version: ${{ matrix.python }} + conda-remove-defaults: true - run: set shell: cmd - - name: Add conda's DLL path - run: | - echo $env:CONDA\Library\bin >> $GITHUB_PATH - echo $env:CONDA_PREFIX\Library\bin >> $GITHUB_PATH - - - uses: ruby/setup-ruby@v1 - if: matrix.ruby_version != 'master-nightly' - with: - ruby-version: ${{ matrix.ruby }} - - run: conda install numpy - run: python -c 'import numpy; print(numpy)' - run: python -c 'import os; print(os.environ)' - - run: bundle install - - - run: rake compile - - run: python lib/pycall/python/investigator.py - run: | @@ -116,12 +208,34 @@ jobs: ruby -Ilib -Iext/pycall -rpycall -e "PyCall.import_module(:numpy)" env: PYTHON: python - continue-on-error: true + # Not rake, which runs extconf.rb again. - run: | echo $env:PATH - rake + ruby test/run-test.rb + if ($LASTEXITCODE) { exit $LASTEXITCODE } + ruby -Iext/pycall -S rspec env: PYTHON: python CONDA_DLL_SEARCH_MODIFICATION_ENABLE: 1 - continue-on-error: true + + # setup-miniconda sets CONDA_PREFIX to the activated environment. + - name: Find Python in CONDA_PREFIX + run: | + # Hide every python.exe on PATH, so that PyCall has to find Python by itself. + $env:PATH = ($env:PATH -split ';' | Where-Object { + $_ -and -not (Test-Path (Join-Path $_ python.exe)) -and -not (Test-Path (Join-Path $_ python3.exe)) + }) -join ';' + if (Get-Command python, python3 -ErrorAction SilentlyContinue) { throw 'Python is still on PATH' } + Remove-Item Env:PYTHON -ErrorAction SilentlyContinue + @' + require 'pycall' + prefix = PyCall.sys.prefix + puts prefix + abort "Unexpected Python: #{prefix}" unless File.identical?(prefix, ENV['CONDA_PREFIX']) + # These load DLLs that are next to python3XX.dll, or in Library\bin of conda. + %w[ctypes ssl sqlite3 numpy].each {|name| PyCall.import_module(name) } + '@ | ruby -Ilib -Iext/pycall + if ($LASTEXITCODE) { exit $LASTEXITCODE } + env: + PYCALL_DEBUG_FIND_LIBPYTHON: 1 diff --git a/README.md b/README.md index 49eb621..e851bca 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,10 @@ you can change the Python version by setting the `PYTHON` environment variable to the path of the `python` executable. When `PYTHON` is not specified, pycall.rb tries to use `python3` first, -and then tries to use `python`. +and then tries to use `python`. On Windows, it then tries `python.exe` in +`CONDA_PREFIX`, and then the installations registered in the Windows registry +under `Software\Python`, which includes Anaconda when it was registered by its +installer. ### Releasing the RubyVM GVL during Python function calls diff --git a/lib/pycall/libpython/finder.rb b/lib/pycall/libpython/finder.rb index ddfcc85..b878bde 100644 --- a/lib/pycall/libpython/finder.rb +++ b/lib/pycall/libpython/finder.rb @@ -1,4 +1,5 @@ require 'pycall/error' +require 'pycall/libpython/finder_for_windows' require 'fiddle' require 'pathname' @@ -38,6 +39,8 @@ def find_python_config(python = nil) end def find_libpython(python = nil) + return FinderForWindows.find_libpython(python) if windows? + debug_report("find_libpython(#{python.inspect})") python, python_config = find_python_config(python) suffix = python_config[:SHLIB_SUFFIX] diff --git a/lib/pycall/libpython/finder_for_windows.rb b/lib/pycall/libpython/finder_for_windows.rb new file mode 100644 index 0000000..cfe5f0f --- /dev/null +++ b/lib/pycall/libpython/finder_for_windows.rb @@ -0,0 +1,286 @@ +require 'pycall/error' +require 'fiddle' + +module PyCall + module LibPython + # Finds and loads the Python library on Windows. + # + # Finder.find_libpython delegates here on Windows, where finding Python + # and loading its DLL differ from the other platforms: + # + # - Python is often not on PATH, as with Anaconda, so CONDA_PREFIX and the + # PEP 514 entries in the registry are searched too. + # - sysconfig has no SHLIB_SUFFIX, and the DLL is named like python311.dll. + # - The dependencies of the DLL are not found in its own folder. + module FinderForWindows + DEFAULT_PYTHON = [ + -'python3', + -'python', + ].freeze + + # The location of the PEP 514 registry entries. + PYTHON_REGISTRY_KEY = -'Software\Python' + + # PEP 514 has companies register side by side. Prefer the reference + # implementation like the py launcher does. + PYTHON_REGISTRY_PREFERRED_COMPANY = -'PythonCore' + + DEFAULT_SHLIB_SUFFIX = -'.dll' + + class << self + def find_libpython(python = nil) + debug_report("find_libpython(#{python.inspect})") + python, python_config = find_python_config(python) + suffix = shlib_suffix(python_config) + + use_conda = (ENV.fetch("CONDA_PREFIX", nil) == File.dirname(python_config[:executable])) + python_home = if !ENV.key?("PYTHONHOME") || use_conda + python_config[:PYTHONHOME] + else + ENV["PYTHONHOME"] + end + ENV["PYTHONHOME"] = python_home + + candidate_paths(python_config) do |path| + debug_report("Candidate: #{path}") + normalized = Finder.normalize_path(path, suffix, false) + if normalized + debug_report("Trying to dlopen: #{normalized}") + begin + return dlopen(normalized) + rescue Fiddle::DLError + debug_report "dlopen(#{normalized.inspect}) => #{$!.class}: #{$!.message}" + end + else + debug_report("Not found.") + end + end + raise ::PyCall::PythonNotFound + end + + def find_python_config(python = nil) + found = if python + # An explicitly given python must not be replaced by another. + first_python_config(Array(python)) + else + first_python_config(DEFAULT_PYTHON) || + first_python_config(python_candidates) + end + found or raise ::PyCall::PythonNotFound + end + + # Python executables that can be found without PATH. + def python_candidates + (conda_prefix_pythons + registry_pythons).uniq + end + + def conda_prefix_pythons + prefix = ENV['CONDA_PREFIX'] + return [] if prefix.nil? || prefix.empty? + [File.join(prefix, 'python.exe')].select {|path| File.file?(path) } + end + + # Python executables registered in the registry, best one first. + def registry_pythons + installs = registry_installs.select {|install| registry_install_loadable?(install) } + sorted = installs.each_with_index.sort_by do |install, index| + [registry_company_rank(install), registry_version_key(install), index] + end + pythons = sorted.map do |install, _| + install[:executable_path] || + (File.join(install[:install_path], 'python.exe') if install[:install_path]) + end + pythons.compact.select {|path| File.file?(path) } + end + + # Reads the PEP 514 entries: + # {HKCU,HKLM}\Software\Python\\\InstallPath + def registry_installs(key_path = PYTHON_REGISTRY_KEY) + require 'win32/registry' + [ + Win32::Registry::HKEY_CURRENT_USER, + Win32::Registry::HKEY_LOCAL_MACHINE, + ].flat_map {|hive| read_registry_installs(hive, key_path) } + rescue LoadError + debug_report("Unable to read the registry: #{$!.message}") + [] + end + + def investigate_python_config(python) + python_env = { 'PYTHONIOENCODING' => 'UTF-8' } + debug_report("investigate_python_config(#{python.inspect})") + # The Microsoft Store alias python.exe complains on stderr, which would + # be printed on every start even when a later candidate works. + popen_options = debug? ? {} : { err: File::NULL } + IO.popen(python_env, [python, Finder.python_investigator_py], 'r', **popen_options) do |io| + {}.tap do |config| + io.each_line do |line| + next unless line =~ /: / + key, value = line.chomp.split(': ', 2) + case value + when 'True', 'true', 'False', 'false' + value = (value == 'True' || value == 'true') + end + config[key.to_sym] = value if value != 'None' + end + end + end + rescue Errno::ENOENT + raise PyCall::PythonInvestigationFailed + end + + def candidate_names(python_config) + suffix = shlib_suffix(python_config) + names = [] + names << python_config[:LDLIBRARY] if python_config[:LDLIBRARY] + if python_config[:LIBRARY] + ext = File.extname(python_config[:LIBRARY]) + names << python_config[:LIBRARY].chomp(ext) + suffix + end + version = python_config[:VERSION].to_s + [ + # The name of the DLL has no dot, like python311.dll. + "python#{version.delete('.')}", + "python#{version}#{python_config[:ABIFLAGS]}", + "python#{version}", + "python", + ].each do |stem| + names << "#{stem}#{suffix}" + end + + names.uniq! + + debug_report("candidate_names: #{names}") + return names + end + + def candidate_paths(python_config) + # The candidate library that linked by executable + yield python_config[:linked_libpython] + + lib_basenames = candidate_names(python_config) + Finder.make_libpaths(python_config).each do |dir| + lib_basenames.each do |name| + yield File.join(dir, name) + end + end + end + + private + + def first_python_config(python_commands) + python_commands.each do |python_cmd| + begin + python_config = investigate_python_config(python_cmd) + return [python_cmd, python_config] unless python_config.empty? + rescue + end + end + nil + end + + def shlib_suffix(python_config) + python_config[:SHLIB_SUFFIX] || DEFAULT_SHLIB_SUFFIX + end + + def read_registry_installs(hive, key_path) + installs = [] + open_registry_key(hive, key_path) do |root| + each_registry_subkey(root) do |company, company_key| + each_registry_subkey(company_key) do |tag, tag_key| + open_registry_key(tag_key, 'InstallPath') do |install_path_key| + installs << { + company: company, + tag: tag, + sys_version: registry_value(tag_key, 'SysVersion'), + sys_architecture: registry_value(tag_key, 'SysArchitecture'), + install_path: registry_value(install_path_key, ''), + executable_path: registry_value(install_path_key, 'ExecutablePath'), + } + end + end + end + end + installs + end + + def each_registry_subkey(key) + key.keys.each do |name| + open_registry_key(key, name) {|subkey| yield name, subkey } + end + end + + # An entry that is missing or unreadable must not hide the others. + def open_registry_key(key, name, &block) + key.open(name, &block) + rescue Win32::Registry::Error + debug_report("Unable to read the registry key #{name.inspect}: #{$!.message}") + end + + def registry_value(key, name) + key[name] + rescue Win32::Registry::Error + nil + end + + # A library for another architecture cannot be loaded into this process. + def registry_install_loadable?(install) + bits = Fiddle::SIZEOF_VOIDP * 8 + if install[:sys_architecture] + install[:sys_architecture] == "#{bits}bit" + else + !install[:tag].end_with?(bits == 64 ? '-32' : '-64') + end + end + + def registry_company_rank(install) + install[:company] == PYTHON_REGISTRY_PREFERRED_COMPANY ? 0 : 1 + end + + # Sorts newer versions first. + def registry_version_key(install) + version = install[:sys_version] || install[:tag] + version.scan(/\d+/).map {|part| -part.to_i } + end + + def dlopen(libname) + add_python_dll_directories(libname) + Fiddle.dlopen(libname).tap do |handle| + debug_report("dlopen(#{libname.inspect}) = #{handle.inspect}") if handle + end + end + + # Windows does not look for the dependencies of a DLL in the folder of + # that DLL when it is loaded by an absolute path, and python3xx.dll needs + # its neighbors like zlib.dll. Fiddle then reports the misleading + # "No such file or directory". Library\bin is the other folder of DLLs + # in a conda environment, which `conda activate` would add to PATH. + def add_python_dll_directories(libname) + dir = File.dirname(libname) + [dir, File.join(dir, 'Library', 'bin')].select {|path| File.directory?(path) }.reverse_each do |path| + add_dll_directory(path) + end + end + + def add_dll_directory(path) + debug_report("add_dll_directory(#{path.inspect})") + if defined?(RubyInstaller::Runtime) + # RubyInstaller excludes PATH from the DLL search. + RubyInstaller::Runtime.add_dll_directory(path) + else + ENV['PATH'] = [path.tr('/', '\\'), ENV['PATH']].compact.join(File::PATH_SEPARATOR) + end + end + + def debug_report(message) + return unless debug? + $stderr.puts "DEBUG(find_libpython) #{message}" + end + + def debug? + ENV['PYCALL_DEBUG_FIND_LIBPYTHON'] == '1' + end + end + end + end +end diff --git a/spec/pycall/libpython/finder_for_windows_spec.rb b/spec/pycall/libpython/finder_for_windows_spec.rb new file mode 100644 index 0000000..ccc91b3 --- /dev/null +++ b/spec/pycall/libpython/finder_for_windows_spec.rb @@ -0,0 +1,92 @@ +require 'spec_helper' +require 'fileutils' +require 'tmpdir' + +# Finding Python outside of PATH and loading its DLL are tested with real +# installations by the Windows workflow. These cover what it cannot set up. +module PyCall + module LibPython + ::RSpec.describe FinderForWindows, if: Fiddle::WINDOWS do + def touch(*path) + File.join(*path).tap do |file| + FileUtils.mkdir_p(File.dirname(file)) + FileUtils.touch(file) + end + end + + around do |example| + Dir.mktmpdir('pycall-finder') do |dir| + @tmpdir = dir + example.run + end + end + + describe '.find_python_config' do + it 'does not replace an explicitly given python' do + allow(FinderForWindows).to receive(:investigate_python_config).and_return({}) + expect(FinderForWindows).not_to receive(:python_candidates) + expect { FinderForWindows.find_python_config('C:\Missing\python.exe') }.to raise_error(PyCall::PythonNotFound) + end + end + + describe '.registry_pythons' do + def install(company, tag, **values) + { company: company, tag: tag }.merge(values) + end + + def python_in(name) + touch(@tmpdir, name, 'python.exe') + end + + let(:bits) { Fiddle::SIZEOF_VOIDP * 8 } + let(:other_bits) { bits == 64 ? 32 : 64 } + + it 'skips entries that cannot be loaded into this process' do + python = python_in('python') + allow(FinderForWindows).to receive(:registry_installs).and_return([ + install('PythonCore', '3.11', executable_path: python, sys_architecture: "#{other_bits}bit"), + install('PythonCore', "3.10-#{other_bits}", executable_path: python), + install('PythonCore', '3.9', install_path: File.join(@tmpdir, 'gone')), + ]) + expect(FinderForWindows.registry_pythons).to eq([]) + end + + it 'prefers PythonCore, and then newer versions' do + old_core = python_in('core39') + new_core = python_in('core311') + other = python_in('other') + allow(FinderForWindows).to receive(:registry_installs).and_return([ + install('Other', '3.14', executable_path: other), + install('PythonCore', '3.9', executable_path: old_core), + install('PythonCore', '3.11', install_path: File.dirname(new_core)), + ]) + expect(FinderForWindows.registry_pythons).to eq([new_core, old_core, other]) + end + end + + describe 'loading the library without RubyInstaller' do + around do |example| + saved = ENV['PATH'] + example.run + ENV['PATH'] = saved + end + + before do + hide_const('RubyInstaller') + allow(Fiddle).to receive(:dlopen).and_return(:handle) + end + + it 'prepends the folders to PATH with backslashes, the folder of the DLL first' do + bin = File.join(@tmpdir, 'Library', 'bin') + FileUtils.mkdir_p(bin) + before_path = ENV['PATH'] + + FinderForWindows.send(:dlopen, "#{@tmpdir}/python311.dll") + + expected = [@tmpdir, bin].map {|path| path.tr('/', '\\') } + [before_path] + expect(ENV['PATH']).to eq(expected.join(File::PATH_SEPARATOR)) + end + end + end + end +end