user10957988
user10957988

Reputation:

Cannot use fortran code from f2py compile function

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?

Upvotes: 1

Views: 293

Answers (1)

ForceBru
ForceBru

Reputation: 44926

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).

Upvotes: 2

Related Questions