From 0a669ff6330cede417d153d3805b13bbc296379e Mon Sep 17 00:00:00 2001 From: felixmarch Date: Fri, 6 Nov 2026 17:11:33 +0800 Subject: [PATCH 01/10] Fix PyCall::PythonNotFound on Windows Python was not found or failed to load on Windows for three reasons: - Python that is not on PATH was never found. Fall back to python.exe in CONDA_PREFIX, and then to the PEP 514 entries in the registry under Software\Python, which includes ContinuumAnalytics for Anaconda. An explicitly given python is still used alone. - sysconfig has no SHLIB_SUFFIX on Windows, which raised TypeError while building the candidate names. Default it to .dll and add the python311-style name. - Fiddle.dlopen of the right python3xx.dll failed with "No such file or directory". The slashes are not the cause: backslashes fail the same way and forward slashes work once the dependencies resolve. The cause is that dependencies like zlib.dll in the folder of the DLL are not found, and RubyInstaller excludes PATH from the DLL search. Register the folder of the DLL and Library\bin with RubyInstaller::Runtime.add_dll_directory, or prepend them to PATH on other Ruby distributions. Also stop printing the complaint of the Microsoft Store python.exe alias on every start, unless PYCALL_DEBUG_FIND_LIBPYTHON is set. Fixes red-data-tools/pycall.rb#86 Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- lib/pycall/libpython/finder.rb | 175 ++++++++++++++-- spec/pycall/libpython/finder_spec.rb | 303 +++++++++++++++++++++++++++ 3 files changed, 468 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index d72199bc..75aa04fb 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,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 ddfcc853..6168d8ac 100644 --- a/lib/pycall/libpython/finder.rb +++ b/lib/pycall/libpython/finder.rb @@ -25,22 +25,27 @@ class << self -'python', ].freeze + # The location of the PEP 514 registry entries on Windows. + PYTHON_REGISTRY_KEY = -'Software\Python' + + # PEP 514 has companies register side by side. Prefer the reference + # implementation like the py launcher does, then Anaconda. + PYTHON_REGISTRY_COMPANIES = [ + -'PythonCore', + -'ContinuumAnalytics', + ].freeze + def find_python_config(python = nil) - python ||= DEFAULT_PYTHON - Array(python).each do |python_cmd| - begin - python_config = investigate_python_config(python_cmd) - return [python_cmd, python_config] unless python_config.empty? - rescue - end - end - raise ::PyCall::PythonNotFound + found = first_python_config(Array(python || DEFAULT_PYTHON)) + # An explicitly given python must not be silently replaced by another. + found ||= first_python_config(windows_python_candidates) if python.nil? && windows? + found or raise ::PyCall::PythonNotFound end def find_libpython(python = nil) debug_report("find_libpython(#{python.inspect})") python, python_config = find_python_config(python) - suffix = python_config[:SHLIB_SUFFIX] + 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 @@ -69,7 +74,7 @@ def find_libpython(python = nil) def candidate_names(python_config) names = [] names << python_config[:LDLIBRARY] if python_config[:LDLIBRARY] - suffix = python_config[:SHLIB_SUFFIX] + suffix = shlib_suffix(python_config) if python_config[:LIBRARY] ext = File.extname(python_config[:LIBRARY]) names << python_config[:LIBRARY].delete_suffix(ext) + suffix @@ -80,12 +85,15 @@ def candidate_names(python_config) VERSION: python_config[:VERSION], ABIFLAGS: python_config[:ABIFLAGS], } - [ + stems = [ "python%{VERSION}%{ABIFLAGS}" % sysdata, "python%{VERSION}" % sysdata, "python%{v_major}" % sysdata, "python" - ].each do |stem| + ] + # Windows names the library without the dot, like python311.dll. + stems.unshift("python#{python_config[:VERSION].to_s.delete('.')}") if windows? + stems.each do |stem| names << "#{dlprefix}#{stem}#{suffix}" end @@ -141,7 +149,10 @@ def remove_suffix_apple(path) def investigate_python_config(python) python_env = { 'PYTHONIOENCODING' => 'UTF-8' } debug_report("investigate_python_config(#{python.inspect})") - IO.popen(python_env, [python, python_investigator_py], 'r') do |io| + # The Microsoft Store alias python.exe complains on stderr, which would + # be printed on every start even when a later candidate works. + popen_options = windows? && !debug? ? { err: File::NULL } : {} + IO.popen(python_env, [python, python_investigator_py], 'r', **popen_options) do |io| {}.tap do |config| io.each_line do |line| next unless line =~ /: / @@ -186,8 +197,121 @@ def make_libpaths(python_config) return libpaths end + # Python executables that can be found on Windows without PATH. + def windows_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 Windows 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 + 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 + + # sysconfig has no SHLIB_SUFFIX on Windows. + def shlib_suffix(python_config) + python_config[:SHLIB_SUFFIX] || ('.dll' if windows?) + 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) + PYTHON_REGISTRY_COMPANIES.index(install[:company]) || PYTHON_REGISTRY_COMPANIES.size + 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 windows? Fiddle::WINDOWS end @@ -197,11 +321,34 @@ def apple? end def dlopen(libname) + add_python_dll_directories(libname) if windows? 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::Runtime.respond_to?(:add_dll_directory) + # 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}" diff --git a/spec/pycall/libpython/finder_spec.rb b/spec/pycall/libpython/finder_spec.rb index 30df7c84..ab665ea5 100644 --- a/spec/pycall/libpython/finder_spec.rb +++ b/spec/pycall/libpython/finder_spec.rb @@ -1,4 +1,5 @@ require 'spec_helper' +require 'fileutils' require 'tmpdir' module PyCall @@ -19,6 +20,308 @@ module LibPython it { is_expected.to be_a(Hash) } end + + # Everything except the real registry access runs on all platforms, so that + # the Windows behavior is also covered by the CI on Linux and macOS. + context 'on Windows' do + before do + allow(Finder).to receive(:windows?).and_return(true) + end + + 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 + let(:config) { { executable: 'python.exe' } } + + before do + allow(Finder).to receive(:investigate_python_config).and_return({}) + end + + it 'prefers python on PATH' do + allow(Finder).to receive(:investigate_python_config).with('python3').and_return(config) + expect(Finder).not_to receive(:windows_python_candidates) + expect(Finder.find_python_config).to eq(['python3', config]) + end + + it 'falls back to the candidates outside of PATH' do + allow(Finder).to receive(:windows_python_candidates).and_return(['C:\Conda\python.exe']) + allow(Finder).to receive(:investigate_python_config).with('C:\Conda\python.exe').and_return(config) + expect(Finder.find_python_config).to eq(['C:\Conda\python.exe', config]) + end + + it 'does not replace an explicitly given python' do + expect(Finder).not_to receive(:windows_python_candidates) + expect { Finder.find_python_config('C:\Missing\python.exe') }.to raise_error(PyCall::PythonNotFound) + end + + it 'raises PythonNotFound when no candidate works' do + allow(Finder).to receive(:windows_python_candidates).and_return([]) + expect { Finder.find_python_config }.to raise_error(PyCall::PythonNotFound) + end + end + + describe '.conda_prefix_pythons' do + around do |example| + saved = ENV['CONDA_PREFIX'] + example.run + ENV['CONDA_PREFIX'] = saved + end + + it 'finds python.exe in CONDA_PREFIX' do + python = touch(@tmpdir, 'python.exe') + ENV['CONDA_PREFIX'] = @tmpdir + expect(Finder.conda_prefix_pythons).to eq([python]) + end + + it 'ignores a CONDA_PREFIX without python.exe' do + ENV['CONDA_PREFIX'] = @tmpdir + expect(Finder.conda_prefix_pythons).to eq([]) + end + + it 'ignores a missing CONDA_PREFIX' do + ENV.delete('CONDA_PREFIX') + expect(Finder.conda_prefix_pythons).to eq([]) + 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 'finds Anaconda registered under ContinuumAnalytics' do + python = python_in('anaconda') + allow(Finder).to receive(:registry_installs).and_return([ + install('ContinuumAnalytics', 'Anaconda311-64', executable_path: python), + ]) + expect(Finder.registry_pythons).to eq([python]) + end + + it 'derives python.exe from InstallPath without ExecutablePath' do + python = python_in('core') + allow(Finder).to receive(:registry_installs).and_return([ + install('PythonCore', '3.11', install_path: File.dirname(python)), + ]) + expect(Finder.registry_pythons).to eq([python]) + end + + it 'skips entries without an existing executable' do + allow(Finder).to receive(:registry_installs).and_return([ + install('PythonCore', '3.11', install_path: File.join(@tmpdir, 'gone')), + install('PythonCore', '3.10'), + ]) + expect(Finder.registry_pythons).to eq([]) + end + + it 'skips libraries that cannot be loaded into this process' do + python = python_in('other') + allow(Finder).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), + ]) + expect(Finder.registry_pythons).to eq([]) + end + + it 'keeps an entry of the architecture of this process' do + python = python_in('same') + allow(Finder).to receive(:registry_installs).and_return([ + install('PythonCore', "3.11-#{other_bits}", executable_path: python, sys_architecture: "#{bits}bit"), + ]) + expect(Finder.registry_pythons).to eq([python]) + end + + it 'orders by company and then by descending version' do + old_core = python_in('core39') + new_core = python_in('core311') + conda = python_in('conda') + other = python_in('other') + allow(Finder).to receive(:registry_installs).and_return([ + install('Other', '3.14', executable_path: other), + install('ContinuumAnalytics', 'Anaconda3-64', executable_path: conda, sys_version: '3.13'), + install('PythonCore', '3.9', executable_path: old_core), + install('PythonCore', '3.11', executable_path: new_core), + ]) + expect(Finder.registry_pythons).to eq([new_core, old_core, conda, other]) + end + end + + describe '.candidate_names' do + # This is what the investigator reports for Python 3.11 of Anaconda. + let(:config) { { VERSION: '3.11' } } + + it 'uses .dll without SHLIB_SUFFIX, and the name without the dot' do + expect(Finder.candidate_names(config).first).to eq('python311.dll') + end + + it 'keeps the names from sysconfig first' do + names = Finder.candidate_names(config.merge(LDLIBRARY: 'python3.11.dll')) + expect(names.first).to eq('python3.11.dll') + expect(names).to include('python311.dll') + end + + it 'handles LIBRARY without SHLIB_SUFFIX' do + names = Finder.candidate_names(config.merge(LIBRARY: 'python311.lib')) + expect(names.first).to eq('python311.dll') + end + end + + describe 'loading the library' do + let(:runtime) { double('RubyInstaller::Runtime', add_dll_directory: nil) } + + before do + allow(Fiddle).to receive(:dlopen).and_return(:handle) + end + + context 'with RubyInstaller' do + before do + stub_const('RubyInstaller::Runtime', runtime) + end + + it 'registers the folder of the DLL and Library\bin before loading' do + bin = File.join(@tmpdir, 'Library', 'bin') + FileUtils.mkdir_p(bin) + calls = [] + allow(runtime).to receive(:add_dll_directory) {|path| calls << path } + allow(Fiddle).to receive(:dlopen) { calls << :dlopen; :handle } + + expect(Finder.send(:dlopen, "#{@tmpdir}/python311.dll")).to eq(:handle) + expect(calls.last).to eq(:dlopen) + expect(calls[0...-1]).to contain_exactly(@tmpdir, bin) + end + + it 'does not register a Library\bin that does not exist' do + Finder.send(:dlopen, "#{@tmpdir}/python311.dll") + expect(runtime).to have_received(:add_dll_directory).once.with(@tmpdir) + end + end + + context 'without RubyInstaller' do + around do |example| + saved = ENV['PATH'] + example.run + ENV['PATH'] = saved + end + + before do + hide_const('RubyInstaller') + 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'] + + Finder.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 + + context 'not on Windows' do + before do + allow(Finder).to receive(:windows?).and_return(false) + end + + it 'does not look outside of PATH' do + allow(Finder).to receive(:investigate_python_config).and_return({}) + expect(Finder).not_to receive(:windows_python_candidates) + expect { Finder.find_python_config }.to raise_error(PyCall::PythonNotFound) + end + + it 'does not add the name without the dot' do + names = Finder.candidate_names(VERSION: '3.11', SHLIB_SUFFIX: '.so') + expect(names).to include('libpython3.11.so') + expect(names).not_to include('libpython311.so') + end + + it 'does not touch the DLL search path' do + allow(Fiddle).to receive(:dlopen).and_return(:handle) + expect(Finder).not_to receive(:add_dll_directory) + Finder.send(:dlopen, '/usr/lib/libpython3.11.so') + end + end + + describe '.registry_installs', if: Fiddle::WINDOWS do + # Uses a scratch key instead of Software\Python, so that the specs neither + # depend on nor change what is installed on the machine. + let(:key_path) { "Software\\PyCallSpec-#{Process.pid}-#{rand(1 << 32)}" } + + before do + require 'win32/registry' + end + + after do + Win32::Registry::HKEY_CURRENT_USER.delete_key(key_path, true) + end + + def write_entry(path, values) + Win32::Registry::HKEY_CURRENT_USER.create("#{key_path}\\#{path}") do |key| + values.each {|name, value| key[name] = value } + end + end + + def installs + Finder.registry_installs(key_path) + end + + it 'reads the entries of all companies' do + write_entry('ContinuumAnalytics\Anaconda311-64', 'SysVersion' => '3.11', 'SysArchitecture' => '64bit') + write_entry('ContinuumAnalytics\Anaconda311-64\InstallPath', + '' => 'C:\Anaconda3', 'ExecutablePath' => 'C:\Anaconda3\python.exe') + write_entry('PythonCore\3.12\InstallPath', '' => 'C:\Python312') + + expect(installs).to contain_exactly( + { + company: 'ContinuumAnalytics', + tag: 'Anaconda311-64', + sys_version: '3.11', + sys_architecture: '64bit', + install_path: 'C:\Anaconda3', + executable_path: 'C:\Anaconda3\python.exe', + }, + { + company: 'PythonCore', + tag: '3.12', + sys_version: nil, + sys_architecture: nil, + install_path: 'C:\Python312', + executable_path: nil, + }, + ) + end + + it 'ignores entries without InstallPath' do + write_entry('PyLauncher\Language', 'SysVersion' => '3.11') + expect(installs).to eq([]) + end + + it 'returns nothing when the key does not exist' do + write_entry('Unrelated', {}) + expect(Finder.registry_installs("#{key_path}\\Missing")).to eq([]) + end + end end end end From 3eddea54ea4226cb3ec035c155ba66f91523f8de Mon Sep 17 00:00:00 2001 From: felixmarch Date: Fri, 6 Nov 2026 18:02:29 +0800 Subject: [PATCH 02/10] Use String#chomp to support Ruby 2.4 String#delete_suffix requires Ruby 2.5, so candidate_names raised NoMethodError on Ruby 2.4 when python_config has LIBRARY. It was not noticed because candidate_names only runs when the first candidate fails to load, until the new finder spec reached it. Co-Authored-By: Claude Opus 5.5 --- lib/pycall/libpython/finder.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pycall/libpython/finder.rb b/lib/pycall/libpython/finder.rb index 6168d8ac..f11426f0 100644 --- a/lib/pycall/libpython/finder.rb +++ b/lib/pycall/libpython/finder.rb @@ -77,7 +77,7 @@ def candidate_names(python_config) suffix = shlib_suffix(python_config) if python_config[:LIBRARY] ext = File.extname(python_config[:LIBRARY]) - names << python_config[:LIBRARY].delete_suffix(ext) + suffix + names << python_config[:LIBRARY].chomp(ext) + suffix end dlprefix = if windows? then "" else "lib" end sysdata = { From 3120ab73b95b71c0384981363c146f10172c0e11 Mon Sep 17 00:00:00 2001 From: felixmarch Date: Sun, 8 Nov 2026 16:06:53 +0800 Subject: [PATCH 03/10] Move the Windows implementation into FinderForWindows As requested in the review, Finder.find_libpython now delegates to FinderForWindows.find_libpython at its beginning on Windows, and Finder is back to its previous flow. FinderForWindows keeps the Windows behavior as it was: finding Python in CONDA_PREFIX and the registry, the .dll suffix and python311.dll-style names, and registering the DLL folders before Fiddle.dlopen. It reuses Finder.normalize_path, Finder.make_libpaths and the investigator script. It now raises PythonNotFound when no library can be loaded, instead of returning the result of the last candidate. Co-Authored-By: Claude Opus 5.5 --- lib/pycall/libpython/finder.rb | 180 +--------- lib/pycall/libpython/finder_for_windows.rb | 289 ++++++++++++++++ .../libpython/finder_for_windows_spec.rb | 318 ++++++++++++++++++ spec/pycall/libpython/finder_spec.rb | 305 +---------------- 4 files changed, 634 insertions(+), 458 deletions(-) create mode 100644 lib/pycall/libpython/finder_for_windows.rb create mode 100644 spec/pycall/libpython/finder_for_windows_spec.rb diff --git a/lib/pycall/libpython/finder.rb b/lib/pycall/libpython/finder.rb index f11426f0..b878bde8 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' @@ -25,27 +26,24 @@ class << self -'python', ].freeze - # The location of the PEP 514 registry entries on Windows. - PYTHON_REGISTRY_KEY = -'Software\Python' - - # PEP 514 has companies register side by side. Prefer the reference - # implementation like the py launcher does, then Anaconda. - PYTHON_REGISTRY_COMPANIES = [ - -'PythonCore', - -'ContinuumAnalytics', - ].freeze - def find_python_config(python = nil) - found = first_python_config(Array(python || DEFAULT_PYTHON)) - # An explicitly given python must not be silently replaced by another. - found ||= first_python_config(windows_python_candidates) if python.nil? && windows? - found or raise ::PyCall::PythonNotFound + python ||= DEFAULT_PYTHON + Array(python).each do |python_cmd| + begin + python_config = investigate_python_config(python_cmd) + return [python_cmd, python_config] unless python_config.empty? + rescue + end + end + raise ::PyCall::PythonNotFound 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 = shlib_suffix(python_config) + suffix = python_config[:SHLIB_SUFFIX] use_conda = (ENV.fetch("CONDA_PREFIX", nil) == File.dirname(python_config[:executable])) python_home = if !ENV.key?("PYTHONHOME") || use_conda @@ -74,10 +72,10 @@ def find_libpython(python = nil) def candidate_names(python_config) names = [] names << python_config[:LDLIBRARY] if python_config[:LDLIBRARY] - suffix = shlib_suffix(python_config) + suffix = python_config[:SHLIB_SUFFIX] if python_config[:LIBRARY] ext = File.extname(python_config[:LIBRARY]) - names << python_config[:LIBRARY].chomp(ext) + suffix + names << python_config[:LIBRARY].delete_suffix(ext) + suffix end dlprefix = if windows? then "" else "lib" end sysdata = { @@ -85,15 +83,12 @@ def candidate_names(python_config) VERSION: python_config[:VERSION], ABIFLAGS: python_config[:ABIFLAGS], } - stems = [ + [ "python%{VERSION}%{ABIFLAGS}" % sysdata, "python%{VERSION}" % sysdata, "python%{v_major}" % sysdata, "python" - ] - # Windows names the library without the dot, like python311.dll. - stems.unshift("python#{python_config[:VERSION].to_s.delete('.')}") if windows? - stems.each do |stem| + ].each do |stem| names << "#{dlprefix}#{stem}#{suffix}" end @@ -149,10 +144,7 @@ def remove_suffix_apple(path) 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 = windows? && !debug? ? { err: File::NULL } : {} - IO.popen(python_env, [python, python_investigator_py], 'r', **popen_options) do |io| + IO.popen(python_env, [python, python_investigator_py], 'r') do |io| {}.tap do |config| io.each_line do |line| next unless line =~ /: / @@ -197,121 +189,8 @@ def make_libpaths(python_config) return libpaths end - # Python executables that can be found on Windows without PATH. - def windows_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 Windows 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 - 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 - - # sysconfig has no SHLIB_SUFFIX on Windows. - def shlib_suffix(python_config) - python_config[:SHLIB_SUFFIX] || ('.dll' if windows?) - 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) - PYTHON_REGISTRY_COMPANIES.index(install[:company]) || PYTHON_REGISTRY_COMPANIES.size - 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 windows? Fiddle::WINDOWS end @@ -321,34 +200,11 @@ def apple? end def dlopen(libname) - add_python_dll_directories(libname) if windows? 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::Runtime.respond_to?(:add_dll_directory) - # 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}" diff --git a/lib/pycall/libpython/finder_for_windows.rb b/lib/pycall/libpython/finder_for_windows.rb new file mode 100644 index 00000000..6c47bd10 --- /dev/null +++ b/lib/pycall/libpython/finder_for_windows.rb @@ -0,0 +1,289 @@ +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, then Anaconda. + PYTHON_REGISTRY_COMPANIES = [ + -'PythonCore', + -'ContinuumAnalytics', + ].freeze + + 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) + PYTHON_REGISTRY_COMPANIES.index(install[:company]) || PYTHON_REGISTRY_COMPANIES.size + 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::Runtime.respond_to?(:add_dll_directory) + # 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? + @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 00000000..71829e84 --- /dev/null +++ b/spec/pycall/libpython/finder_for_windows_spec.rb @@ -0,0 +1,318 @@ +require 'spec_helper' +require 'fileutils' +require 'tmpdir' + +module PyCall + module LibPython + # Everything except the real registry access runs on all platforms, so that + # the Windows behavior is also covered by the CI on Linux and macOS. + ::RSpec.describe FinderForWindows 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 + let(:config) { { executable: 'python.exe' } } + + before do + allow(FinderForWindows).to receive(:investigate_python_config).and_return({}) + end + + it 'prefers python on PATH' do + allow(FinderForWindows).to receive(:investigate_python_config).with('python3').and_return(config) + expect(FinderForWindows).not_to receive(:python_candidates) + expect(FinderForWindows.find_python_config).to eq(['python3', config]) + end + + it 'falls back to the candidates outside of PATH' do + allow(FinderForWindows).to receive(:python_candidates).and_return(['C:\Conda\python.exe']) + allow(FinderForWindows).to receive(:investigate_python_config).with('C:\Conda\python.exe').and_return(config) + expect(FinderForWindows.find_python_config).to eq(['C:\Conda\python.exe', config]) + end + + it 'does not replace an explicitly given python' do + expect(FinderForWindows).not_to receive(:python_candidates) + expect { FinderForWindows.find_python_config('C:\Missing\python.exe') }.to raise_error(PyCall::PythonNotFound) + end + + it 'raises PythonNotFound when no candidate works' do + allow(FinderForWindows).to receive(:python_candidates).and_return([]) + expect { FinderForWindows.find_python_config }.to raise_error(PyCall::PythonNotFound) + end + end + + describe '.find_libpython' do + around do |example| + saved = ENV['PYTHONHOME'] + example.run + ENV['PYTHONHOME'] = saved + end + + let(:config) do + { + executable: File.join(@tmpdir, 'python.exe'), + exec_prefix: @tmpdir, + VERSION: '3.11', + PYTHONHOME: @tmpdir, + } + end + + before do + allow(FinderForWindows).to receive(:find_python_config).and_return(['python', config]) + allow(FinderForWindows).to receive(:add_dll_directory) + end + + it 'loads python311.dll next to the executable' do + dll = touch(@tmpdir, 'python311.dll') + expect(Fiddle).to receive(:dlopen).with(File.realpath(dll)).and_return(:handle) + expect(FinderForWindows.find_libpython).to eq(:handle) + end + + it 'tries the next candidate when loading fails' do + linked = touch(@tmpdir, 'linked', 'python311.dll') + dll = touch(@tmpdir, 'python311.dll') + config[:linked_libpython] = linked + allow(Fiddle).to receive(:dlopen).with(File.realpath(linked)).and_raise(Fiddle::DLError) + allow(Fiddle).to receive(:dlopen).with(File.realpath(dll)).and_return(:handle) + expect(FinderForWindows.find_libpython).to eq(:handle) + end + + it 'raises PythonNotFound when no library can be loaded' do + expect { FinderForWindows.find_libpython }.to raise_error(PyCall::PythonNotFound) + end + end + + describe '.conda_prefix_pythons' do + around do |example| + saved = ENV['CONDA_PREFIX'] + example.run + ENV['CONDA_PREFIX'] = saved + end + + it 'finds python.exe in CONDA_PREFIX' do + python = touch(@tmpdir, 'python.exe') + ENV['CONDA_PREFIX'] = @tmpdir + expect(FinderForWindows.conda_prefix_pythons).to eq([python]) + end + + it 'ignores a CONDA_PREFIX without python.exe' do + ENV['CONDA_PREFIX'] = @tmpdir + expect(FinderForWindows.conda_prefix_pythons).to eq([]) + end + + it 'ignores a missing CONDA_PREFIX' do + ENV.delete('CONDA_PREFIX') + expect(FinderForWindows.conda_prefix_pythons).to eq([]) + 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 'finds Anaconda registered under ContinuumAnalytics' do + python = python_in('anaconda') + allow(FinderForWindows).to receive(:registry_installs).and_return([ + install('ContinuumAnalytics', 'Anaconda311-64', executable_path: python), + ]) + expect(FinderForWindows.registry_pythons).to eq([python]) + end + + it 'derives python.exe from InstallPath without ExecutablePath' do + python = python_in('core') + allow(FinderForWindows).to receive(:registry_installs).and_return([ + install('PythonCore', '3.11', install_path: File.dirname(python)), + ]) + expect(FinderForWindows.registry_pythons).to eq([python]) + end + + it 'skips entries without an existing executable' do + allow(FinderForWindows).to receive(:registry_installs).and_return([ + install('PythonCore', '3.11', install_path: File.join(@tmpdir, 'gone')), + install('PythonCore', '3.10'), + ]) + expect(FinderForWindows.registry_pythons).to eq([]) + end + + it 'skips libraries that cannot be loaded into this process' do + python = python_in('other') + 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), + ]) + expect(FinderForWindows.registry_pythons).to eq([]) + end + + it 'keeps an entry of the architecture of this process' do + python = python_in('same') + allow(FinderForWindows).to receive(:registry_installs).and_return([ + install('PythonCore', "3.11-#{other_bits}", executable_path: python, sys_architecture: "#{bits}bit"), + ]) + expect(FinderForWindows.registry_pythons).to eq([python]) + end + + it 'orders by company and then by descending version' do + old_core = python_in('core39') + new_core = python_in('core311') + conda = python_in('conda') + other = python_in('other') + allow(FinderForWindows).to receive(:registry_installs).and_return([ + install('Other', '3.14', executable_path: other), + install('ContinuumAnalytics', 'Anaconda3-64', executable_path: conda, sys_version: '3.13'), + install('PythonCore', '3.9', executable_path: old_core), + install('PythonCore', '3.11', executable_path: new_core), + ]) + expect(FinderForWindows.registry_pythons).to eq([new_core, old_core, conda, other]) + end + end + + describe '.candidate_names' do + # This is what the investigator reports for Python 3.11 of Anaconda. + let(:config) { { VERSION: '3.11' } } + + it 'uses .dll without SHLIB_SUFFIX, and the name without the dot' do + expect(FinderForWindows.candidate_names(config).first).to eq('python311.dll') + end + + it 'keeps the names from sysconfig first' do + names = FinderForWindows.candidate_names(config.merge(LDLIBRARY: 'python3.11.dll')) + expect(names.first).to eq('python3.11.dll') + expect(names).to include('python311.dll') + end + + it 'handles LIBRARY without SHLIB_SUFFIX' do + names = FinderForWindows.candidate_names(config.merge(LIBRARY: 'python311.lib')) + expect(names.first).to eq('python311.dll') + end + end + + describe 'loading the library' do + let(:runtime) { double('RubyInstaller::Runtime', add_dll_directory: nil) } + + before do + allow(Fiddle).to receive(:dlopen).and_return(:handle) + end + + context 'with RubyInstaller' do + before do + stub_const('RubyInstaller::Runtime', runtime) + end + + it 'registers the folder of the DLL and Library\bin before loading' do + bin = File.join(@tmpdir, 'Library', 'bin') + FileUtils.mkdir_p(bin) + calls = [] + allow(runtime).to receive(:add_dll_directory) {|path| calls << path } + allow(Fiddle).to receive(:dlopen) { calls << :dlopen; :handle } + + expect(FinderForWindows.send(:dlopen, "#{@tmpdir}/python311.dll")).to eq(:handle) + expect(calls.last).to eq(:dlopen) + expect(calls[0...-1]).to contain_exactly(@tmpdir, bin) + end + + it 'does not register a Library\bin that does not exist' do + FinderForWindows.send(:dlopen, "#{@tmpdir}/python311.dll") + expect(runtime).to have_received(:add_dll_directory).once.with(@tmpdir) + end + end + + context 'without RubyInstaller' do + around do |example| + saved = ENV['PATH'] + example.run + ENV['PATH'] = saved + end + + before do + hide_const('RubyInstaller') + 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 + + describe '.registry_installs', if: Fiddle::WINDOWS do + # Uses a scratch key instead of Software\Python, so that the specs neither + # depend on nor change what is installed on the machine. + let(:key_path) { "Software\\PyCallSpec-#{Process.pid}-#{rand(1 << 32)}" } + + before do + require 'win32/registry' + end + + after do + Win32::Registry::HKEY_CURRENT_USER.delete_key(key_path, true) + end + + def write_entry(path, values) + Win32::Registry::HKEY_CURRENT_USER.create("#{key_path}\\#{path}") do |key| + values.each {|name, value| key[name] = value } + end + end + + it 'reads the entries of all companies' do + write_entry('ContinuumAnalytics\Anaconda311-64', 'SysVersion' => '3.11', 'SysArchitecture' => '64bit') + write_entry('ContinuumAnalytics\Anaconda311-64\InstallPath', + '' => 'C:\Anaconda3', 'ExecutablePath' => 'C:\Anaconda3\python.exe') + write_entry('PythonCore\3.12\InstallPath', '' => 'C:\Python312') + + expect(FinderForWindows.registry_installs(key_path)).to contain_exactly( + { + company: 'ContinuumAnalytics', + tag: 'Anaconda311-64', + sys_version: '3.11', + sys_architecture: '64bit', + install_path: 'C:\Anaconda3', + executable_path: 'C:\Anaconda3\python.exe', + }, + { + company: 'PythonCore', + tag: '3.12', + sys_version: nil, + sys_architecture: nil, + install_path: 'C:\Python312', + executable_path: nil, + }, + ) + end + + it 'ignores entries without InstallPath' do + write_entry('PyLauncher\Language', 'SysVersion' => '3.11') + expect(FinderForWindows.registry_installs(key_path)).to eq([]) + end + + it 'returns nothing when the key does not exist' do + write_entry('Unrelated', {}) + expect(FinderForWindows.registry_installs("#{key_path}\\Missing")).to eq([]) + end + end + end + end +end diff --git a/spec/pycall/libpython/finder_spec.rb b/spec/pycall/libpython/finder_spec.rb index ab665ea5..19d8b8d5 100644 --- a/spec/pycall/libpython/finder_spec.rb +++ b/spec/pycall/libpython/finder_spec.rb @@ -1,5 +1,4 @@ require 'spec_helper' -require 'fileutils' require 'tmpdir' module PyCall @@ -21,305 +20,19 @@ module LibPython it { is_expected.to be_a(Hash) } end - # Everything except the real registry access runs on all platforms, so that - # the Windows behavior is also covered by the CI on Linux and macOS. - context 'on Windows' do - before do + describe '.find_libpython' do + it 'delegates to FinderForWindows on Windows' do allow(Finder).to receive(:windows?).and_return(true) + expect(FinderForWindows).to receive(:find_libpython).with('python.exe').and_return(:handle) + expect(Finder).not_to receive(:find_python_config) + expect(Finder.find_libpython('python.exe')).to eq(:handle) end - 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 - let(:config) { { executable: 'python.exe' } } - - before do - allow(Finder).to receive(:investigate_python_config).and_return({}) - end - - it 'prefers python on PATH' do - allow(Finder).to receive(:investigate_python_config).with('python3').and_return(config) - expect(Finder).not_to receive(:windows_python_candidates) - expect(Finder.find_python_config).to eq(['python3', config]) - end - - it 'falls back to the candidates outside of PATH' do - allow(Finder).to receive(:windows_python_candidates).and_return(['C:\Conda\python.exe']) - allow(Finder).to receive(:investigate_python_config).with('C:\Conda\python.exe').and_return(config) - expect(Finder.find_python_config).to eq(['C:\Conda\python.exe', config]) - end - - it 'does not replace an explicitly given python' do - expect(Finder).not_to receive(:windows_python_candidates) - expect { Finder.find_python_config('C:\Missing\python.exe') }.to raise_error(PyCall::PythonNotFound) - end - - it 'raises PythonNotFound when no candidate works' do - allow(Finder).to receive(:windows_python_candidates).and_return([]) - expect { Finder.find_python_config }.to raise_error(PyCall::PythonNotFound) - end - end - - describe '.conda_prefix_pythons' do - around do |example| - saved = ENV['CONDA_PREFIX'] - example.run - ENV['CONDA_PREFIX'] = saved - end - - it 'finds python.exe in CONDA_PREFIX' do - python = touch(@tmpdir, 'python.exe') - ENV['CONDA_PREFIX'] = @tmpdir - expect(Finder.conda_prefix_pythons).to eq([python]) - end - - it 'ignores a CONDA_PREFIX without python.exe' do - ENV['CONDA_PREFIX'] = @tmpdir - expect(Finder.conda_prefix_pythons).to eq([]) - end - - it 'ignores a missing CONDA_PREFIX' do - ENV.delete('CONDA_PREFIX') - expect(Finder.conda_prefix_pythons).to eq([]) - 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 'finds Anaconda registered under ContinuumAnalytics' do - python = python_in('anaconda') - allow(Finder).to receive(:registry_installs).and_return([ - install('ContinuumAnalytics', 'Anaconda311-64', executable_path: python), - ]) - expect(Finder.registry_pythons).to eq([python]) - end - - it 'derives python.exe from InstallPath without ExecutablePath' do - python = python_in('core') - allow(Finder).to receive(:registry_installs).and_return([ - install('PythonCore', '3.11', install_path: File.dirname(python)), - ]) - expect(Finder.registry_pythons).to eq([python]) - end - - it 'skips entries without an existing executable' do - allow(Finder).to receive(:registry_installs).and_return([ - install('PythonCore', '3.11', install_path: File.join(@tmpdir, 'gone')), - install('PythonCore', '3.10'), - ]) - expect(Finder.registry_pythons).to eq([]) - end - - it 'skips libraries that cannot be loaded into this process' do - python = python_in('other') - allow(Finder).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), - ]) - expect(Finder.registry_pythons).to eq([]) - end - - it 'keeps an entry of the architecture of this process' do - python = python_in('same') - allow(Finder).to receive(:registry_installs).and_return([ - install('PythonCore', "3.11-#{other_bits}", executable_path: python, sys_architecture: "#{bits}bit"), - ]) - expect(Finder.registry_pythons).to eq([python]) - end - - it 'orders by company and then by descending version' do - old_core = python_in('core39') - new_core = python_in('core311') - conda = python_in('conda') - other = python_in('other') - allow(Finder).to receive(:registry_installs).and_return([ - install('Other', '3.14', executable_path: other), - install('ContinuumAnalytics', 'Anaconda3-64', executable_path: conda, sys_version: '3.13'), - install('PythonCore', '3.9', executable_path: old_core), - install('PythonCore', '3.11', executable_path: new_core), - ]) - expect(Finder.registry_pythons).to eq([new_core, old_core, conda, other]) - end - end - - describe '.candidate_names' do - # This is what the investigator reports for Python 3.11 of Anaconda. - let(:config) { { VERSION: '3.11' } } - - it 'uses .dll without SHLIB_SUFFIX, and the name without the dot' do - expect(Finder.candidate_names(config).first).to eq('python311.dll') - end - - it 'keeps the names from sysconfig first' do - names = Finder.candidate_names(config.merge(LDLIBRARY: 'python3.11.dll')) - expect(names.first).to eq('python3.11.dll') - expect(names).to include('python311.dll') - end - - it 'handles LIBRARY without SHLIB_SUFFIX' do - names = Finder.candidate_names(config.merge(LIBRARY: 'python311.lib')) - expect(names.first).to eq('python311.dll') - end - end - - describe 'loading the library' do - let(:runtime) { double('RubyInstaller::Runtime', add_dll_directory: nil) } - - before do - allow(Fiddle).to receive(:dlopen).and_return(:handle) - end - - context 'with RubyInstaller' do - before do - stub_const('RubyInstaller::Runtime', runtime) - end - - it 'registers the folder of the DLL and Library\bin before loading' do - bin = File.join(@tmpdir, 'Library', 'bin') - FileUtils.mkdir_p(bin) - calls = [] - allow(runtime).to receive(:add_dll_directory) {|path| calls << path } - allow(Fiddle).to receive(:dlopen) { calls << :dlopen; :handle } - - expect(Finder.send(:dlopen, "#{@tmpdir}/python311.dll")).to eq(:handle) - expect(calls.last).to eq(:dlopen) - expect(calls[0...-1]).to contain_exactly(@tmpdir, bin) - end - - it 'does not register a Library\bin that does not exist' do - Finder.send(:dlopen, "#{@tmpdir}/python311.dll") - expect(runtime).to have_received(:add_dll_directory).once.with(@tmpdir) - end - end - - context 'without RubyInstaller' do - around do |example| - saved = ENV['PATH'] - example.run - ENV['PATH'] = saved - end - - before do - hide_const('RubyInstaller') - 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'] - - Finder.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 - - context 'not on Windows' do - before do + it 'does not delegate on the other platforms' do allow(Finder).to receive(:windows?).and_return(false) - end - - it 'does not look outside of PATH' do - allow(Finder).to receive(:investigate_python_config).and_return({}) - expect(Finder).not_to receive(:windows_python_candidates) - expect { Finder.find_python_config }.to raise_error(PyCall::PythonNotFound) - end - - it 'does not add the name without the dot' do - names = Finder.candidate_names(VERSION: '3.11', SHLIB_SUFFIX: '.so') - expect(names).to include('libpython3.11.so') - expect(names).not_to include('libpython311.so') - end - - it 'does not touch the DLL search path' do - allow(Fiddle).to receive(:dlopen).and_return(:handle) - expect(Finder).not_to receive(:add_dll_directory) - Finder.send(:dlopen, '/usr/lib/libpython3.11.so') - end - end - - describe '.registry_installs', if: Fiddle::WINDOWS do - # Uses a scratch key instead of Software\Python, so that the specs neither - # depend on nor change what is installed on the machine. - let(:key_path) { "Software\\PyCallSpec-#{Process.pid}-#{rand(1 << 32)}" } - - before do - require 'win32/registry' - end - - after do - Win32::Registry::HKEY_CURRENT_USER.delete_key(key_path, true) - end - - def write_entry(path, values) - Win32::Registry::HKEY_CURRENT_USER.create("#{key_path}\\#{path}") do |key| - values.each {|name, value| key[name] = value } - end - end - - def installs - Finder.registry_installs(key_path) - end - - it 'reads the entries of all companies' do - write_entry('ContinuumAnalytics\Anaconda311-64', 'SysVersion' => '3.11', 'SysArchitecture' => '64bit') - write_entry('ContinuumAnalytics\Anaconda311-64\InstallPath', - '' => 'C:\Anaconda3', 'ExecutablePath' => 'C:\Anaconda3\python.exe') - write_entry('PythonCore\3.12\InstallPath', '' => 'C:\Python312') - - expect(installs).to contain_exactly( - { - company: 'ContinuumAnalytics', - tag: 'Anaconda311-64', - sys_version: '3.11', - sys_architecture: '64bit', - install_path: 'C:\Anaconda3', - executable_path: 'C:\Anaconda3\python.exe', - }, - { - company: 'PythonCore', - tag: '3.12', - sys_version: nil, - sys_architecture: nil, - install_path: 'C:\Python312', - executable_path: nil, - }, - ) - end - - it 'ignores entries without InstallPath' do - write_entry('PyLauncher\Language', 'SysVersion' => '3.11') - expect(installs).to eq([]) - end - - it 'returns nothing when the key does not exist' do - write_entry('Unrelated', {}) - expect(Finder.registry_installs("#{key_path}\\Missing")).to eq([]) + expect(FinderForWindows).not_to receive(:find_libpython) + allow(Finder).to receive(:find_python_config).and_raise(PyCall::PythonNotFound) + expect { Finder.find_libpython('python3') }.to raise_error(PyCall::PythonNotFound) end end end From 6d301f1ca728b349811f59a4bea7f1ebe2f1e75c Mon Sep 17 00:00:00 2001 From: felixmarch Date: Wed, 11 Nov 2026 18:25:40 +0800 Subject: [PATCH 04/10] Run FinderForWindows specs only on Windows As requested in the review, put the `if: Fiddle::WINDOWS` condition on the whole FinderForWindows spec instead of only on the registry specs. Co-Authored-By: Claude Opus 5.5 --- spec/pycall/libpython/finder_for_windows_spec.rb | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/spec/pycall/libpython/finder_for_windows_spec.rb b/spec/pycall/libpython/finder_for_windows_spec.rb index 71829e84..f2722981 100644 --- a/spec/pycall/libpython/finder_for_windows_spec.rb +++ b/spec/pycall/libpython/finder_for_windows_spec.rb @@ -4,9 +4,7 @@ module PyCall module LibPython - # Everything except the real registry access runs on all platforms, so that - # the Windows behavior is also covered by the CI on Linux and macOS. - ::RSpec.describe FinderForWindows do + ::RSpec.describe FinderForWindows, if: Fiddle::WINDOWS do def touch(*path) File.join(*path).tap do |file| FileUtils.mkdir_p(File.dirname(file)) @@ -258,7 +256,7 @@ def python_in(name) end end - describe '.registry_installs', if: Fiddle::WINDOWS do + describe '.registry_installs' do # Uses a scratch key instead of Software\Python, so that the specs neither # depend on nor change what is installed on the machine. let(:key_path) { "Software\\PyCallSpec-#{Process.pid}-#{rand(1 << 32)}" } From d5c2fa64dc5ed7136aa7846d08cf23741a47a65d Mon Sep 17 00:00:00 2001 From: felixmarch Date: Thu, 12 Nov 2026 08:12:10 +0800 Subject: [PATCH 05/10] Test finding Python outside of PATH on Windows CI As requested in the review, add a discovery job to the Windows workflow that uses real Python installations instead of mocks. Each job hides every python.exe on PATH and checks that PyCall loads the expected Python, imports modules that need DLLs, and passes the test suites: - registry-pythoncore: Python registered under PythonCore - registry-anaconda: Miniconda installed with /RegisterPython=1, the only Python registered (under ContinuumAnalytics) - conda-prefix: a conda environment given by CONDA_PREFIX finder_spec.rb is skipped there because it runs python on PATH. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/windows.yml | 111 ++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 94af8552..d320b502 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -59,6 +59,117 @@ jobs: env: PYTHON: python + # Python installations that are not on PATH, which PyCall has to find by itself: + # - registry-pythoncore: Python from python.org registered under Software\Python\PythonCore + # - registry-anaconda: Miniconda registered under Software\Python\ContinuumAnalytics + # - conda-prefix: a conda environment given by CONDA_PREFIX + discovery: + name: discovery:${{ matrix.source }}/ruby-${{ matrix.ruby }} + runs-on: windows-latest + + strategy: + fail-fast: false + matrix: + ruby: + - "3.3" + source: + - registry-pythoncore + - registry-anaconda + - conda-prefix + + 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 + + - uses: actions/setup-python@v7 + if: matrix.source == 'registry-pythoncore' + with: + python-version: 3.x + + - name: Expect Python registered under PythonCore + if: matrix.source == 'registry-pythoncore' + run: | + $prefixes = Get-ChildItem HKCU:\Software\Python\PythonCore, HKLM:\SOFTWARE\Python\PythonCore -ErrorAction SilentlyContinue | + ForEach-Object { (Get-ItemProperty -LiteralPath "$($_.PSPath)\InstallPath" -ErrorAction SilentlyContinue).'(default)' } | + Where-Object { $_ } + if (-not $prefixes) { throw 'No Python is registered under PythonCore' } + Write-Host "Registered: $($prefixes -join ', ')" + "EXPECTED_PYTHON_PREFIXES=$($prefixes -join ';')" >> $env:GITHUB_ENV + + - name: Install Miniconda registered as the system Python + if: matrix.source == 'registry-anaconda' + run: | + # Remove the registrations of the runner image, so that only Miniconda is registered. + Remove-Item -Recurse -Force HKLM:\SOFTWARE\Python, HKLM:\SOFTWARE\WOW6432Node\Python, HKCU:\Software\Python -ErrorAction SilentlyContinue + $installer = Join-Path $env:RUNNER_TEMP miniconda.exe + $prefix = Join-Path $env:RUNNER_TEMP miniconda3 + Invoke-WebRequest https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exe -OutFile $installer + Start-Process -Wait -FilePath $installer -ArgumentList '/S', '/InstallationType=JustMe', '/RegisterPython=1', '/AddToPath=0', "/D=$prefix" + reg query HKCU\Software\Python /s + "EXPECTED_PYTHON_PREFIXES=$prefix" >> $env:GITHUB_ENV + + - uses: conda-incubator/setup-miniconda@v4 + if: matrix.source == 'conda-prefix' + with: + activate-environment: test + python-version: 3.12 + channels: conda-forge + conda-remove-defaults: true + + - name: Expect the conda environment + if: matrix.source == 'conda-prefix' + run: | + conda install -y numpy + $prefix = python -c "import sys; print(sys.prefix)" + "EXPECTED_PYTHON_PREFIXES=$prefix" >> $env:GITHUB_ENV + "PYCALL_TEST_CONDA_PREFIX=$prefix" >> $env:GITHUB_ENV + + - name: Find Python that is not on PATH + 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' } + # Only the conda-prefix job sets CONDA_PREFIX. + $env:CONDA_PREFIX = $env:PYCALL_TEST_CONDA_PREFIX + $env:PYTHON = $null + + @' + require 'pycall' + puts PyCall::PYTHON_DESCRIPTION + prefix = PyCall.sys.prefix + puts "sys.prefix: #{prefix}" + expected = ENV['EXPECTED_PYTHON_PREFIXES'].split(';') + unless expected.any? {|path| File.identical?(path, prefix) } + abort "Expected Python in #{expected.join(' or ')}, but used #{prefix}" + end + # These load DLLs that are next to python3XX.dll, or in Library\bin of conda. + %w[ctypes ssl sqlite3].each {|name| PyCall.import_module(name) } + PyCall.import_module('numpy') if ENV['PYCALL_TEST_CONDA_PREFIX'] + '@ | ruby -Ilib -Iext/pycall + if ($LASTEXITCODE) { exit $LASTEXITCODE } + + # 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 From baf150b38345e55445aea2ecdbae57c24b4d98fa Mon Sep 17 00:00:00 2001 From: felixmarch Date: Thu, 12 Nov 2026 08:59:56 +0800 Subject: [PATCH 06/10] Install numpy and use one registered Python in Windows discovery CI The registry jobs found the expected Python, but two specs failed because numpy was not installed there. Install numpy in both of them. The runner image registers every Python in its tool cache under PythonCore, so the registry-pythoncore job now removes all of them except the Python of setup-python, and expects exactly that one. Miniconda installed with /RegisterPython=1 registers itself under PythonCore, not under ContinuumAnalytics, so rename registry-anaconda to registry-miniconda and correct the comment. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/windows.yml | 49 +++++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index d320b502..15d79904 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -60,8 +60,9 @@ jobs: PYTHON: python # Python installations that are not on PATH, which PyCall has to find by itself: - # - registry-pythoncore: Python from python.org registered under Software\Python\PythonCore - # - registry-anaconda: Miniconda registered under Software\Python\ContinuumAnalytics + # - registry-pythoncore: Python of setup-python, registered under Software\Python\PythonCore + # - registry-miniconda: Miniconda installed with /RegisterPython=1, which registers itself + # under Software\Python\PythonCore as well # - conda-prefix: a conda environment given by CONDA_PREFIX discovery: name: discovery:${{ matrix.source }}/ruby-${{ matrix.ruby }} @@ -74,7 +75,7 @@ jobs: - "3.3" source: - registry-pythoncore - - registry-anaconda + - registry-miniconda - conda-prefix defaults: @@ -95,22 +96,36 @@ jobs: - run: rake compile - uses: actions/setup-python@v7 + id: setup-python if: matrix.source == 'registry-pythoncore' with: python-version: 3.x - - name: Expect Python registered under PythonCore + - name: Leave only the Python of setup-python registered if: matrix.source == 'registry-pythoncore' run: | - $prefixes = Get-ChildItem HKCU:\Software\Python\PythonCore, HKLM:\SOFTWARE\Python\PythonCore -ErrorAction SilentlyContinue | - ForEach-Object { (Get-ItemProperty -LiteralPath "$($_.PSPath)\InstallPath" -ErrorAction SilentlyContinue).'(default)' } | - Where-Object { $_ } - if (-not $prefixes) { throw 'No Python is registered under PythonCore' } - Write-Host "Registered: $($prefixes -join ', ')" - "EXPECTED_PYTHON_PREFIXES=$($prefixes -join ';')" >> $env:GITHUB_ENV + $python = '${{ steps.setup-python.outputs.python-path }}' + $prefix = & $python -c "import sys; print(sys.prefix)" + & $python -m pip install numpy + if ($LASTEXITCODE) { exit $LASTEXITCODE } + # The runner image registers every Python in its tool cache, so remove the others. + Remove-Item -Recurse -Force HKLM:\SOFTWARE\WOW6432Node\Python -ErrorAction SilentlyContinue + $found = $false + foreach ($key in @(Get-ChildItem HKCU:\Software\Python\PythonCore, HKLM:\SOFTWARE\Python\PythonCore -ErrorAction SilentlyContinue)) { + $installPath = (Get-ItemProperty -LiteralPath "$($key.PSPath)\InstallPath" -ErrorAction SilentlyContinue).'(default)' + if ($installPath -and $installPath.TrimEnd('\') -ieq $prefix.TrimEnd('\')) { + Write-Host "Keep $($key.Name): $installPath" + $found = $true + } else { + Write-Host "Remove $($key.Name): $installPath" + Remove-Item -Recurse -Force -LiteralPath $key.PSPath + } + } + if (-not $found) { throw "$prefix is not registered under PythonCore" } + "EXPECTED_PYTHON_PREFIX=$prefix" >> $env:GITHUB_ENV - name: Install Miniconda registered as the system Python - if: matrix.source == 'registry-anaconda' + if: matrix.source == 'registry-miniconda' run: | # Remove the registrations of the runner image, so that only Miniconda is registered. Remove-Item -Recurse -Force HKLM:\SOFTWARE\Python, HKLM:\SOFTWARE\WOW6432Node\Python, HKCU:\Software\Python -ErrorAction SilentlyContinue @@ -118,8 +133,10 @@ jobs: $prefix = Join-Path $env:RUNNER_TEMP miniconda3 Invoke-WebRequest https://repo.anaconda.com/miniconda/Miniconda3-latest-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_PREFIXES=$prefix" >> $env:GITHUB_ENV + "EXPECTED_PYTHON_PREFIX=$prefix" >> $env:GITHUB_ENV - uses: conda-incubator/setup-miniconda@v4 if: matrix.source == 'conda-prefix' @@ -134,7 +151,7 @@ jobs: run: | conda install -y numpy $prefix = python -c "import sys; print(sys.prefix)" - "EXPECTED_PYTHON_PREFIXES=$prefix" >> $env:GITHUB_ENV + "EXPECTED_PYTHON_PREFIX=$prefix" >> $env:GITHUB_ENV "PYCALL_TEST_CONDA_PREFIX=$prefix" >> $env:GITHUB_ENV - name: Find Python that is not on PATH @@ -153,9 +170,9 @@ jobs: puts PyCall::PYTHON_DESCRIPTION prefix = PyCall.sys.prefix puts "sys.prefix: #{prefix}" - expected = ENV['EXPECTED_PYTHON_PREFIXES'].split(';') - unless expected.any? {|path| File.identical?(path, prefix) } - abort "Expected Python in #{expected.join(' or ')}, but used #{prefix}" + expected = ENV.fetch('EXPECTED_PYTHON_PREFIX') + unless File.identical?(expected, prefix) + abort "Expected Python in #{expected}, but used #{prefix}" end # These load DLLs that are next to python3XX.dll, or in Library\bin of conda. %w[ctypes ssl sqlite3].each {|name| PyCall.import_module(name) } From ba6f707692bb5ad05ce682c29b51f480fbf5034f Mon Sep 17 00:00:00 2001 From: felixmarch Date: Thu, 12 Nov 2026 12:44:44 +0800 Subject: [PATCH 07/10] Address the review of the Windows finder and its CI - Prefer only PythonCore in the registry. ContinuumAnalytics was written by old Anaconda installers; such entries are still found, after PythonCore, like those of any other company. - Call RubyInstaller::Runtime.add_dll_directory whenever RubyInstaller::Runtime is defined, which has it since RubyInstaller 2.4.1-1. - Read PYCALL_DEBUG_FIND_LIBPYTHON each time, since @debug ||= did not cache a false result anyway. - Install Miniforge instead of Miniconda in the discovery jobs, so that they use neither Anaconda's installers nor its default channels. - Keep only the specs for what the discovery jobs cannot cover: an explicitly given python, the order and the architecture of the registry entries, and loading without RubyInstaller. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/windows.yml | 18 +- lib/pycall/libpython/finder_for_windows.rb | 13 +- .../libpython/finder_for_windows_spec.rb | 269 ++---------------- spec/pycall/libpython/finder_spec.rb | 16 -- 4 files changed, 37 insertions(+), 279 deletions(-) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 15d79904..8a43f1ec 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -61,7 +61,7 @@ jobs: # Python installations that are not on PATH, which PyCall has to find by itself: # - registry-pythoncore: Python of setup-python, registered under Software\Python\PythonCore - # - registry-miniconda: Miniconda installed with /RegisterPython=1, which registers itself + # - registry-miniforge: Miniforge installed with /RegisterPython=1, which registers itself # under Software\Python\PythonCore as well # - conda-prefix: a conda environment given by CONDA_PREFIX discovery: @@ -75,7 +75,7 @@ jobs: - "3.3" source: - registry-pythoncore - - registry-miniconda + - registry-miniforge - conda-prefix defaults: @@ -124,14 +124,14 @@ jobs: if (-not $found) { throw "$prefix is not registered under PythonCore" } "EXPECTED_PYTHON_PREFIX=$prefix" >> $env:GITHUB_ENV - - name: Install Miniconda registered as the system Python - if: matrix.source == 'registry-miniconda' + - name: Install Miniforge registered as the system Python + if: matrix.source == 'registry-miniforge' run: | - # Remove the registrations of the runner image, so that only Miniconda is registered. + # 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 miniconda.exe - $prefix = Join-Path $env:RUNNER_TEMP miniconda3 - Invoke-WebRequest https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exe -OutFile $installer + $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 } @@ -141,9 +141,9 @@ jobs: - uses: conda-incubator/setup-miniconda@v4 if: matrix.source == 'conda-prefix' with: + miniforge-version: latest activate-environment: test python-version: 3.12 - channels: conda-forge conda-remove-defaults: true - name: Expect the conda environment diff --git a/lib/pycall/libpython/finder_for_windows.rb b/lib/pycall/libpython/finder_for_windows.rb index 6c47bd10..cfe5f0f5 100644 --- a/lib/pycall/libpython/finder_for_windows.rb +++ b/lib/pycall/libpython/finder_for_windows.rb @@ -22,11 +22,8 @@ module FinderForWindows PYTHON_REGISTRY_KEY = -'Software\Python' # PEP 514 has companies register side by side. Prefer the reference - # implementation like the py launcher does, then Anaconda. - PYTHON_REGISTRY_COMPANIES = [ - -'PythonCore', - -'ContinuumAnalytics', - ].freeze + # implementation like the py launcher does. + PYTHON_REGISTRY_PREFERRED_COMPANY = -'PythonCore' DEFAULT_SHLIB_SUFFIX = -'.dll' @@ -237,7 +234,7 @@ def registry_install_loadable?(install) end def registry_company_rank(install) - PYTHON_REGISTRY_COMPANIES.index(install[:company]) || PYTHON_REGISTRY_COMPANIES.size + install[:company] == PYTHON_REGISTRY_PREFERRED_COMPANY ? 0 : 1 end # Sorts newer versions first. @@ -267,7 +264,7 @@ def add_python_dll_directories(libname) def add_dll_directory(path) debug_report("add_dll_directory(#{path.inspect})") - if defined?(RubyInstaller::Runtime) && RubyInstaller::Runtime.respond_to?(:add_dll_directory) + if defined?(RubyInstaller::Runtime) # RubyInstaller excludes PATH from the DLL search. RubyInstaller::Runtime.add_dll_directory(path) else @@ -281,7 +278,7 @@ def debug_report(message) end def debug? - @debug ||= (ENV['PYCALL_DEBUG_FIND_LIBPYTHON'] == '1') + ENV['PYCALL_DEBUG_FIND_LIBPYTHON'] == '1' end end end diff --git a/spec/pycall/libpython/finder_for_windows_spec.rb b/spec/pycall/libpython/finder_for_windows_spec.rb index f2722981..561e48cc 100644 --- a/spec/pycall/libpython/finder_for_windows_spec.rb +++ b/spec/pycall/libpython/finder_for_windows_spec.rb @@ -2,6 +2,9 @@ require 'fileutils' require 'tmpdir' +# Finding Python outside of PATH and loading its DLL are tested with real +# installations by the discovery job of the Windows workflow. These cover +# what that job cannot set up. module PyCall module LibPython ::RSpec.describe FinderForWindows, if: Fiddle::WINDOWS do @@ -20,98 +23,11 @@ def touch(*path) end describe '.find_python_config' do - let(:config) { { executable: 'python.exe' } } - - before do - allow(FinderForWindows).to receive(:investigate_python_config).and_return({}) - end - - it 'prefers python on PATH' do - allow(FinderForWindows).to receive(:investigate_python_config).with('python3').and_return(config) - expect(FinderForWindows).not_to receive(:python_candidates) - expect(FinderForWindows.find_python_config).to eq(['python3', config]) - end - - it 'falls back to the candidates outside of PATH' do - allow(FinderForWindows).to receive(:python_candidates).and_return(['C:\Conda\python.exe']) - allow(FinderForWindows).to receive(:investigate_python_config).with('C:\Conda\python.exe').and_return(config) - expect(FinderForWindows.find_python_config).to eq(['C:\Conda\python.exe', config]) - end - 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 - - it 'raises PythonNotFound when no candidate works' do - allow(FinderForWindows).to receive(:python_candidates).and_return([]) - expect { FinderForWindows.find_python_config }.to raise_error(PyCall::PythonNotFound) - end - end - - describe '.find_libpython' do - around do |example| - saved = ENV['PYTHONHOME'] - example.run - ENV['PYTHONHOME'] = saved - end - - let(:config) do - { - executable: File.join(@tmpdir, 'python.exe'), - exec_prefix: @tmpdir, - VERSION: '3.11', - PYTHONHOME: @tmpdir, - } - end - - before do - allow(FinderForWindows).to receive(:find_python_config).and_return(['python', config]) - allow(FinderForWindows).to receive(:add_dll_directory) - end - - it 'loads python311.dll next to the executable' do - dll = touch(@tmpdir, 'python311.dll') - expect(Fiddle).to receive(:dlopen).with(File.realpath(dll)).and_return(:handle) - expect(FinderForWindows.find_libpython).to eq(:handle) - end - - it 'tries the next candidate when loading fails' do - linked = touch(@tmpdir, 'linked', 'python311.dll') - dll = touch(@tmpdir, 'python311.dll') - config[:linked_libpython] = linked - allow(Fiddle).to receive(:dlopen).with(File.realpath(linked)).and_raise(Fiddle::DLError) - allow(Fiddle).to receive(:dlopen).with(File.realpath(dll)).and_return(:handle) - expect(FinderForWindows.find_libpython).to eq(:handle) - end - - it 'raises PythonNotFound when no library can be loaded' do - expect { FinderForWindows.find_libpython }.to raise_error(PyCall::PythonNotFound) - end - end - - describe '.conda_prefix_pythons' do - around do |example| - saved = ENV['CONDA_PREFIX'] - example.run - ENV['CONDA_PREFIX'] = saved - end - - it 'finds python.exe in CONDA_PREFIX' do - python = touch(@tmpdir, 'python.exe') - ENV['CONDA_PREFIX'] = @tmpdir - expect(FinderForWindows.conda_prefix_pythons).to eq([python]) - end - - it 'ignores a CONDA_PREFIX without python.exe' do - ENV['CONDA_PREFIX'] = @tmpdir - expect(FinderForWindows.conda_prefix_pythons).to eq([]) - end - - it 'ignores a missing CONDA_PREFIX' do - ENV.delete('CONDA_PREFIX') - expect(FinderForWindows.conda_prefix_pythons).to eq([]) - end end describe '.registry_pythons' do @@ -126,189 +42,50 @@ def python_in(name) let(:bits) { Fiddle::SIZEOF_VOIDP * 8 } let(:other_bits) { bits == 64 ? 32 : 64 } - it 'finds Anaconda registered under ContinuumAnalytics' do - python = python_in('anaconda') - allow(FinderForWindows).to receive(:registry_installs).and_return([ - install('ContinuumAnalytics', 'Anaconda311-64', executable_path: python), - ]) - expect(FinderForWindows.registry_pythons).to eq([python]) - end - - it 'derives python.exe from InstallPath without ExecutablePath' do - python = python_in('core') - allow(FinderForWindows).to receive(:registry_installs).and_return([ - install('PythonCore', '3.11', install_path: File.dirname(python)), - ]) - expect(FinderForWindows.registry_pythons).to eq([python]) - end - - it 'skips entries without an existing executable' do - allow(FinderForWindows).to receive(:registry_installs).and_return([ - install('PythonCore', '3.11', install_path: File.join(@tmpdir, 'gone')), - install('PythonCore', '3.10'), - ]) - expect(FinderForWindows.registry_pythons).to eq([]) - end - - it 'skips libraries that cannot be loaded into this process' do - python = python_in('other') + 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 'keeps an entry of the architecture of this process' do - python = python_in('same') - allow(FinderForWindows).to receive(:registry_installs).and_return([ - install('PythonCore', "3.11-#{other_bits}", executable_path: python, sys_architecture: "#{bits}bit"), - ]) - expect(FinderForWindows.registry_pythons).to eq([python]) - end - - it 'orders by company and then by descending version' do + it 'prefers PythonCore, and then newer versions' do old_core = python_in('core39') new_core = python_in('core311') - conda = python_in('conda') other = python_in('other') allow(FinderForWindows).to receive(:registry_installs).and_return([ install('Other', '3.14', executable_path: other), - install('ContinuumAnalytics', 'Anaconda3-64', executable_path: conda, sys_version: '3.13'), install('PythonCore', '3.9', executable_path: old_core), - install('PythonCore', '3.11', executable_path: new_core), + install('PythonCore', '3.11', install_path: File.dirname(new_core)), ]) - expect(FinderForWindows.registry_pythons).to eq([new_core, old_core, conda, other]) + expect(FinderForWindows.registry_pythons).to eq([new_core, old_core, other]) end end - describe '.candidate_names' do - # This is what the investigator reports for Python 3.11 of Anaconda. - let(:config) { { VERSION: '3.11' } } - - it 'uses .dll without SHLIB_SUFFIX, and the name without the dot' do - expect(FinderForWindows.candidate_names(config).first).to eq('python311.dll') - end - - it 'keeps the names from sysconfig first' do - names = FinderForWindows.candidate_names(config.merge(LDLIBRARY: 'python3.11.dll')) - expect(names.first).to eq('python3.11.dll') - expect(names).to include('python311.dll') - end - - it 'handles LIBRARY without SHLIB_SUFFIX' do - names = FinderForWindows.candidate_names(config.merge(LIBRARY: 'python311.lib')) - expect(names.first).to eq('python311.dll') + describe 'loading the library without RubyInstaller' do + around do |example| + saved = ENV['PATH'] + example.run + ENV['PATH'] = saved end - end - - describe 'loading the library' do - let(:runtime) { double('RubyInstaller::Runtime', add_dll_directory: nil) } before do + hide_const('RubyInstaller') allow(Fiddle).to receive(:dlopen).and_return(:handle) end - context 'with RubyInstaller' do - before do - stub_const('RubyInstaller::Runtime', runtime) - end - - it 'registers the folder of the DLL and Library\bin before loading' do - bin = File.join(@tmpdir, 'Library', 'bin') - FileUtils.mkdir_p(bin) - calls = [] - allow(runtime).to receive(:add_dll_directory) {|path| calls << path } - allow(Fiddle).to receive(:dlopen) { calls << :dlopen; :handle } - - expect(FinderForWindows.send(:dlopen, "#{@tmpdir}/python311.dll")).to eq(:handle) - expect(calls.last).to eq(:dlopen) - expect(calls[0...-1]).to contain_exactly(@tmpdir, bin) - end - - it 'does not register a Library\bin that does not exist' do - FinderForWindows.send(:dlopen, "#{@tmpdir}/python311.dll") - expect(runtime).to have_received(:add_dll_directory).once.with(@tmpdir) - end - end - - context 'without RubyInstaller' do - around do |example| - saved = ENV['PATH'] - example.run - ENV['PATH'] = saved - end - - before do - hide_const('RubyInstaller') - 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 - - describe '.registry_installs' do - # Uses a scratch key instead of Software\Python, so that the specs neither - # depend on nor change what is installed on the machine. - let(:key_path) { "Software\\PyCallSpec-#{Process.pid}-#{rand(1 << 32)}" } - - before do - require 'win32/registry' - end - - after do - Win32::Registry::HKEY_CURRENT_USER.delete_key(key_path, true) - 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'] - def write_entry(path, values) - Win32::Registry::HKEY_CURRENT_USER.create("#{key_path}\\#{path}") do |key| - values.each {|name, value| key[name] = value } - end - end - - it 'reads the entries of all companies' do - write_entry('ContinuumAnalytics\Anaconda311-64', 'SysVersion' => '3.11', 'SysArchitecture' => '64bit') - write_entry('ContinuumAnalytics\Anaconda311-64\InstallPath', - '' => 'C:\Anaconda3', 'ExecutablePath' => 'C:\Anaconda3\python.exe') - write_entry('PythonCore\3.12\InstallPath', '' => 'C:\Python312') - - expect(FinderForWindows.registry_installs(key_path)).to contain_exactly( - { - company: 'ContinuumAnalytics', - tag: 'Anaconda311-64', - sys_version: '3.11', - sys_architecture: '64bit', - install_path: 'C:\Anaconda3', - executable_path: 'C:\Anaconda3\python.exe', - }, - { - company: 'PythonCore', - tag: '3.12', - sys_version: nil, - sys_architecture: nil, - install_path: 'C:\Python312', - executable_path: nil, - }, - ) - end - - it 'ignores entries without InstallPath' do - write_entry('PyLauncher\Language', 'SysVersion' => '3.11') - expect(FinderForWindows.registry_installs(key_path)).to eq([]) - end + FinderForWindows.send(:dlopen, "#{@tmpdir}/python311.dll") - it 'returns nothing when the key does not exist' do - write_entry('Unrelated', {}) - expect(FinderForWindows.registry_installs("#{key_path}\\Missing")).to eq([]) + expected = [@tmpdir, bin].map {|path| path.tr('/', '\\') } + [before_path] + expect(ENV['PATH']).to eq(expected.join(File::PATH_SEPARATOR)) end end end diff --git a/spec/pycall/libpython/finder_spec.rb b/spec/pycall/libpython/finder_spec.rb index 19d8b8d5..30df7c84 100644 --- a/spec/pycall/libpython/finder_spec.rb +++ b/spec/pycall/libpython/finder_spec.rb @@ -19,22 +19,6 @@ module LibPython it { is_expected.to be_a(Hash) } end - - describe '.find_libpython' do - it 'delegates to FinderForWindows on Windows' do - allow(Finder).to receive(:windows?).and_return(true) - expect(FinderForWindows).to receive(:find_libpython).with('python.exe').and_return(:handle) - expect(Finder).not_to receive(:find_python_config) - expect(Finder.find_libpython('python.exe')).to eq(:handle) - end - - it 'does not delegate on the other platforms' do - allow(Finder).to receive(:windows?).and_return(false) - expect(FinderForWindows).not_to receive(:find_libpython) - allow(Finder).to receive(:find_python_config).and_raise(PyCall::PythonNotFound) - expect { Finder.find_libpython('python3') }.to raise_error(PyCall::PythonNotFound) - end - end end end end From 6f6e1595d0ffddd19426152a07e7971f19e61557 Mon Sep 17 00:00:00 2001 From: felixmarch Date: Thu, 12 Nov 2026 15:37:23 +0800 Subject: [PATCH 08/10] Move the discovery checks into the existing Windows jobs As suggested in the review, simplify the workflow: - The test job now also finds Python in the registry after hiding every python.exe on PATH. The runner image registers the Pythons of its tool cache under PythonCore, and the newest one is used, so only standard libraries are imported there. - The conda job now also finds Python in CONDA_PREFIX, which setup-miniconda sets, the same way, and imports numpy too. - The conda job no longer continues on error. Its steps failed on master because SHLIB_SUFFIX is None in conda's Python, and pass now. - Remove the "Add conda's DLL path" step. It wrote to $GITHUB_PATH instead of $env:GITHUB_PATH, so it never changed PATH, and PyCall adds the DLL directories by itself now. - The conda job installs Miniforge instead of using the defaults channel. - Only Miniforge registered by its installer is left in its own job, which still runs the suites with the Python that PyCall finds. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/windows.yml | 132 ++++++++---------- .../libpython/finder_for_windows_spec.rb | 3 +- 2 files changed, 57 insertions(+), 78 deletions(-) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 8a43f1ec..4772577f 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -59,13 +59,33 @@ jobs: env: PYTHON: python - # Python installations that are not on PATH, which PyCall has to find by itself: - # - registry-pythoncore: Python of setup-python, registered under Software\Python\PythonCore - # - registry-miniforge: Miniforge installed with /RegisterPython=1, which registers itself - # under Software\Python\PythonCore as well - # - conda-prefix: a conda environment given by CONDA_PREFIX - discovery: - name: discovery:${{ matrix.source }}/ruby-${{ matrix.ruby }} + # 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: @@ -73,10 +93,6 @@ jobs: matrix: ruby: - "3.3" - source: - - registry-pythoncore - - registry-miniforge - - conda-prefix defaults: run: @@ -95,37 +111,7 @@ jobs: - run: rake compile - - uses: actions/setup-python@v7 - id: setup-python - if: matrix.source == 'registry-pythoncore' - with: - python-version: 3.x - - - name: Leave only the Python of setup-python registered - if: matrix.source == 'registry-pythoncore' - run: | - $python = '${{ steps.setup-python.outputs.python-path }}' - $prefix = & $python -c "import sys; print(sys.prefix)" - & $python -m pip install numpy - if ($LASTEXITCODE) { exit $LASTEXITCODE } - # The runner image registers every Python in its tool cache, so remove the others. - Remove-Item -Recurse -Force HKLM:\SOFTWARE\WOW6432Node\Python -ErrorAction SilentlyContinue - $found = $false - foreach ($key in @(Get-ChildItem HKCU:\Software\Python\PythonCore, HKLM:\SOFTWARE\Python\PythonCore -ErrorAction SilentlyContinue)) { - $installPath = (Get-ItemProperty -LiteralPath "$($key.PSPath)\InstallPath" -ErrorAction SilentlyContinue).'(default)' - if ($installPath -and $installPath.TrimEnd('\') -ieq $prefix.TrimEnd('\')) { - Write-Host "Keep $($key.Name): $installPath" - $found = $true - } else { - Write-Host "Remove $($key.Name): $installPath" - Remove-Item -Recurse -Force -LiteralPath $key.PSPath - } - } - if (-not $found) { throw "$prefix is not registered under PythonCore" } - "EXPECTED_PYTHON_PREFIX=$prefix" >> $env:GITHUB_ENV - - name: Install Miniforge registered as the system Python - if: matrix.source == 'registry-miniforge' 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 @@ -138,48 +124,26 @@ jobs: reg query HKCU\Software\Python /s "EXPECTED_PYTHON_PREFIX=$prefix" >> $env:GITHUB_ENV - - uses: conda-incubator/setup-miniconda@v4 - if: matrix.source == 'conda-prefix' - with: - miniforge-version: latest - activate-environment: test - python-version: 3.12 - conda-remove-defaults: true - - - name: Expect the conda environment - if: matrix.source == 'conda-prefix' - run: | - conda install -y numpy - $prefix = python -c "import sys; print(sys.prefix)" - "EXPECTED_PYTHON_PREFIX=$prefix" >> $env:GITHUB_ENV - "PYCALL_TEST_CONDA_PREFIX=$prefix" >> $env:GITHUB_ENV - - - name: Find Python that is not on PATH + - 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' } - # Only the conda-prefix job sets CONDA_PREFIX. - $env:CONDA_PREFIX = $env:PYCALL_TEST_CONDA_PREFIX - $env:PYTHON = $null - + Remove-Item Env:PYTHON -ErrorAction SilentlyContinue @' require 'pycall' - puts PyCall::PYTHON_DESCRIPTION prefix = PyCall.sys.prefix - puts "sys.prefix: #{prefix}" + puts prefix expected = ENV.fetch('EXPECTED_PYTHON_PREFIX') - unless File.identical?(expected, prefix) - abort "Expected Python in #{expected}, but used #{prefix}" - end + 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].each {|name| PyCall.import_module(name) } - PyCall.import_module('numpy') if ENV['PYCALL_TEST_CONDA_PREFIX'] + %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 } @@ -211,17 +175,14 @@ jobs: - 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: @@ -244,7 +205,6 @@ jobs: ruby -Ilib -Iext/pycall -rpycall -e "PyCall.import_module(:numpy)" env: PYTHON: python - continue-on-error: true - run: | echo $env:PATH @@ -252,4 +212,24 @@ jobs: 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/spec/pycall/libpython/finder_for_windows_spec.rb b/spec/pycall/libpython/finder_for_windows_spec.rb index 561e48cc..ccc91b32 100644 --- a/spec/pycall/libpython/finder_for_windows_spec.rb +++ b/spec/pycall/libpython/finder_for_windows_spec.rb @@ -3,8 +3,7 @@ require 'tmpdir' # Finding Python outside of PATH and loading its DLL are tested with real -# installations by the discovery job of the Windows workflow. These cover -# what that job cannot set up. +# installations by the Windows workflow. These cover what it cannot set up. module PyCall module LibPython ::RSpec.describe FinderForWindows, if: Fiddle::WINDOWS do From 3099185515c9bcb1c0974819ec7fb2e2a1b07c51 Mon Sep 17 00:00:00 2001 From: felixmarch Date: Thu, 12 Nov 2026 15:47:57 +0800 Subject: [PATCH 09/10] Build before activating conda in the Windows conda job With Miniforge, bundle install failed to build fiddle because the compiler of MSYS2 failed while the conda-forge environment came first in PATH. Build the gems and the extension before setup-miniconda, as the former conda-prefix job did. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/windows.yml | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 4772577f..db22911e 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -173,6 +173,17 @@ 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. The activated environment comes first + # in PATH, and the compiler of MSYS2 failed there with conda-forge packages. + - run: bundle install + + - run: rake compile + - uses: conda-incubator/setup-miniconda@v4 with: miniforge-version: latest @@ -183,21 +194,12 @@ jobs: - run: set shell: cmd - - 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: | From cfd2e9f2c4ded29aa1da5f56a558318147b8be54 Mon Sep 17 00:00:00 2001 From: felixmarch Date: Thu, 12 Nov 2026 16:11:14 +0800 Subject: [PATCH 10/10] Run the suites without rake in the Windows conda job rake runs extconf.rb again, because the Makefile depends on its directory, which the build changes after writing the Makefile. The compiler then fails while the conda-forge environment is activated, so run the test and spec suites directly, as the registry job does. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/windows.yml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index db22911e..a878fed8 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -178,8 +178,9 @@ jobs: with: ruby-version: ${{ matrix.ruby }} - # Build before conda is activated. The activated environment comes first - # in PATH, and the compiler of MSYS2 failed there with conda-forge packages. + # 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 @@ -208,9 +209,12 @@ jobs: env: PYTHON: python + # 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