如何在Python中使用f2py模块?编译.so后使用及doc属性问题求助
Hey there! Let's work through your f2py module issues—calling the compiled code and getting proper documentation sorted out step by step.
1. First: How to Call Your Compiled Fortran Module
If you've successfully imported the .so module but don't know what functions/subroutines are available, start with these quick checks:
After importing, use
dir()to list all accessible names in the module:import your_compiled_module print(dir(your_compiled_module))This will show you the names of Fortran subroutines/functions that f2py exposed to Python.
For example, if your Fortran code has a subroutine like:
subroutine calculate_mean(arr, mean_val) implicit none real(8), dimension(:), intent(in) :: arr real(8), intent(out) :: mean_val mean_val = sum(arr) / size(arr) end subroutine calculate_meanYou'd call it in Python like this:
import numpy as np import your_compiled_module test_arr = np.array([1.0, 2.0, 3.0], dtype=np.float64) result = your_compiled_module.calculate_mean(test_arr) print(result)Note: f2py handles most type conversions between NumPy arrays and Fortran arrays automatically, but make sure your dtypes match (e.g.,
float64for Fortran'sreal(8)).
2. Fixing the "No doc Attribute" Issue
You're right that f2py doesn't generate documentation by default—you need to add specific comments to your Fortran code so f2py can create __doc__ attributes (which is what Python's help() function uses, not a doc attribute). Here's how to do it:
Add !f2py Comments to Your Fortran Code
Insert special comments prefixed with !f2py above or inside your subroutines/functions to define intent, types, and descriptions. For example:
!f2py real(8), dimension(:), intent(in) :: arr ! Input 1D array !f2py real(8), intent(out) :: mean_val ! Calculated mean value !f2py doc "Computes the arithmetic mean of a 1D floating-point array" subroutine calculate_mean(arr, mean_val) implicit none real(8), dimension(:), intent(in) :: arr real(8), intent(out) :: mean_val mean_val = sum(arr) / size(arr) end subroutine calculate_mean
Recompile the Module
After adding these comments, recompile your Fortran code with f2py (e.g., f2py -c -m your_compiled_module your_fortran_code.f90).
Check the Documentation Now
Once imported, you can access the docstring via the __doc__ attribute or use Python's built-in help():
import your_compiled_module print(your_compiled_module.calculate_mean.__doc__) # Or use help() for a cleaner formatted output help(your_compiled_module.calculate_mean)
3. Bonus: Generate a Signature File for Debugging
If you want to inspect the exact Python interface f2py will create before compiling, use the -h flag to generate a .pyf signature file:
f2py -h your_module.pyf your_fortran_code.f90
This file will show you how f2py maps Fortran arguments to Python, including intent, types, and array shapes—super helpful for troubleshooting edge cases.
内容的提问来源于stack exchange,提问作者Tom Heeley

