简体   繁体   English

在f2py中使用外部数据文件

[英]Using external data files in f2py

I have some old fortran code that I am wrapping and importing to python using f2py . 我有一些旧的fortran代码,正在包装并使用f2py导入到python中。 The fortran code relies on a data file that resides in the same directory. fortran代码依赖于位于同一目录中的数据文件。 If I start python in that directory, everything works fine. 如果我在该目录中启动python,一切正常。

However, if I import this module from somewhere else, it looks for the files locally and obviously cannot find them. 但是,如果我从其他地方导入该模块,它将在本地查找文件,显然找不到它们。

Is there a way to tell the module where to execute the fortran code (or another clever way around it)? 有没有办法告诉模块在哪里执行fortran代码(或其他巧妙的方法)?

I don't know a lot about f2py but it looks like there is a command line version and a module version. 我对f2py不太了解,但看起来好像有命令行版本和模块版本。

To use the commmand line option, I see two options: 要使用命令行选项,我看到两个选项:

  1. Modify the fortran to find the path 修改fortran以查找路径
  2. Wrap the command line with a wrapper 用包装器包装命令行

For a wrapper, you could use a bash script that does something like this: 对于包装器,可以使用执行以下操作的bash脚本:

#!/bin/sh
dir=$(dirname $0)       # gets relative path
dir=$(readlink -f $dir) # to get absolute
cd $dir
# Now call p2py

If you use the module version, you can use os.chdir() to change the directory before running your pythonized fortran source: 如果使用模块版本,则可以在运行python化的fortran源之前使用os.chdir()更改目录:

fortran_file = "foo.f"
dir = os.path.dirname(os.path.abspath(fortran_file))
os.chdir(dir)
# Now run p2py against fortran_file

Only other option I can think of is to see if you can inject the path into the fortran code. 我能想到的唯一其他选择是查看是否可以将路径注入到fortran代码中。 Maybe you can read the code, change the path in the source in memory, and then use f2py.compile() against that dynamically modified code. 也许您可以阅读代码,更改内存中源代码的路径,然后对动态修改后的代码使用f2py.compile()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM