无法使用 f2py 编译函数中的 Fortran 代码
Cannot use fortran code from f2py compile function
我有以下 Fortran 代码:
!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
而不是使用命令:python -m numpy.f2py -m routines -c routines.f90
,我想从 python 脚本中编译,如下所示:
#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')
但是当我尝试执行此脚本时:python main.py
我收到以下错误:
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'
你能告诉我这是什么问题吗?
open(r'routines.f90', 'r')
打开您的文件以阅读 text (a.k.a. str
),但是,显然,f2py.compile
需要它的第一个参数是 bytes
类型。为了满足这一点,以二进制模式打开文件:
open(r'routines.f90', 'rb')
(另外,r'routines...'
中的第一个r
不需要,直接做'routines.f90'
即可,虽然变化不大。
我有以下 Fortran 代码:
!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
而不是使用命令:python -m numpy.f2py -m routines -c routines.f90
,我想从 python 脚本中编译,如下所示:
#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')
但是当我尝试执行此脚本时:python main.py
我收到以下错误:
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'
你能告诉我这是什么问题吗?
open(r'routines.f90', 'r')
打开您的文件以阅读 text (a.k.a. str
),但是,显然,f2py.compile
需要它的第一个参数是 bytes
类型。为了满足这一点,以二进制模式打开文件:
open(r'routines.f90', 'rb')
(另外,r'routines...'
中的第一个r
不需要,直接做'routines.f90'
即可,虽然变化不大。