如何执行`f2py`?

How to execute `f2py`?

如何包装 f2py 模块?

我的意思是,我正在阅读一些说我应该执行的教程

f2py FIB1.f -m FIB2 -h FIB1.pyf

但是,我不知道我必须在哪里执行它,肯定不是在 spyder 中,或者我做错了什么。

为什么?

因为我执行这段代码,应该从我的 Fortran 子程序中创建 Fortran 的扩展模块 Python,但是会生成错误。

我在 Python 中执行的内容:

import numpy.f2py as f2py

f2py FIB1.f -m FIB2 -h FIB1.pyf

错误是这个:

runfile('F:/SLB/Larryf2py/teste.py', wdir='F:/SLB/Larryf2py')
  File "F:/SLB/Larryf2py/teste.py", line 9
    f2py FIB1.f -m FIB2 -h FIB1.pyf
            ^
SyntaxError: invalid syntax

据我所知,不确定,它应该生成如下内容:

# File setup.py
def configuration(parent_package='',top_path=None):
    from numpy.distutils.misc_util import Configuration
    config = Configuration('',parent_package,top_path)

    config.add_extension('m',
                         sources = ['m.pyf','foo.c'])
    return config
if __name__ == "__main__":
    from numpy.distutils.core import setup
    setup(**configuration(top_path='').todict())

这个生成的示例是针对 C 的,但我认为它也类似于针对 Fortran 的内容。

我怎么看?那我应该运行第一个代码在另一个地方Python...

我尝试重现 this

f2py 不是 Python 命令,您不能在 Python shell 或 .py 源文件中执行它。它是一个可执行命令。您必须在系统的 shell.

中执行它

您仍然没有回答您使用的是哪个操作系统,但如果是 Windows,您必须在 CMD.exe 命令提示符或 PowerShell 中 运行 它。如果它是 Linux 或类似的,则 运行 它在 bash 或类似的 shell 中。您必须 运行 它位于 Fortran 源文件所在的同一目录(文件夹)中。

您是否在 Python 代码中添加了 f2py 命令? 如果是,那就不好了。

f2py FIB1.f -m FIB2 -h FIB1.pyf 需要在命令行中,而不是在任何 *.py 脚本中。

From F2PY Users Guide and Reference Manual f2py is a program/compiler from The purpose of the F2PY –Fortran to Python interface generator– project is to provide a connection between Python and Fortran languages. F2PY is a Python package (with a command line tool f2py and a module f2py2e) that facilitates creating/building Python C/API extension modules that make it possible.

此外,这里详细explanation介绍了如何使用 f2py 。

OP 的问题中可能还有其他问题,但目前最重要的是这个问题。比如Fortran子程序没有使用implicit none,等等

好吧,我找到了答案。

看起来在这个版本的 anaconda 中应该是这样的

Python c:\user\anaconda3\scripts\f2py.py FIB1.f -m FIB2 -h FIB1.py

所以这样 f2py.py 部分就被替换掉了。可以肯定的是,我以后使用这个模块会遇到更多麻烦,但到目前为止,我的疑虑已经很清楚了。

如果您想使用 python 代码将堡垒运行 转换为 python 对象,可以使用以下代码:

 from numpy import f2py

 with open('path_to_fotran_code') as sourcefile:
     sourcecode = sourcefile.read()

 f2py.compile(sourcecode, modulename='test_module', verbose=1,
              extra_args= '--verbose'
                          '--compiler=mingw32')
 import test_module

如果您没有 mingw32,您可以使用 --compile=msvc(我 运行 尝试使用 msvc 时出现问题,我无法通过所有互联网解决这些问题帮助)。
还要确保您的 windows 路径环境配置为指向 fort运行 编译器路径。