1

I have the following Fortran code:

    !routines.f90
    module mymodule
       contains

         function add(a, b)
             real(8), intent(in):: a
             real(8), intent(in):: b
             real(8) :: add
             add = a + b
         end function
    end module

Instead of using the command: python -m numpy.f2py -m routines -c routines.f90, I want to compile from within a python script, as follows:

#main.py
import numpy as np
import numpy.f2py as f2py

with open(r'routines.f90', 'r') as f:
     source = f.read()

 f2py.compile(source, modulename='routines')

 print('OK')

But when I try to execute this script: python main.py I get the following error:

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    f2py.compile(source, modulename='routines')
  File "/home/user1/anaconda3/lib/python3.6/site-packages/numpy/f2py/__init__.py", line 59, in compile
    f.write(source)
  File "/home/user1/anaconda3/lib/python3.6/tempfile.py", line 485, in func_wrapper
    return func(*args, **kwargs)
TypeError: a bytes-like object is required, not 'str'

Could you please tell me what is the issue?

1 Answer 1

2

open(r'routines.f90', 'r') opens your file for reading text (a.k.a. str), but, apparently, f2py.compile requires that its first argument be of type bytes. To satisfy that, open your file in binary mode:

open(r'routines.f90', 'rb')

(Also, there's no need for the first r in r'routines...', you can just do 'routines.f90', although it doesn't change much).

Sign up to request clarification or add additional context in comments.

2 Comments

Now I have another compilation issue with f2py which expect a fixed form fortran file, so I have start all my fortran code at 7'th column to solve that. Could you please tell me how to tell f2py use free form fortran source file? thank you
Add the argument extension='.f90' to the compile function call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.