Skip to content

Instantly share code, notes, and snippets.

@arogozhnikov
Created November 17, 2015 15:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arogozhnikov/844ab967cf6d255390ea to your computer and use it in GitHub Desktop.
Save arogozhnikov/844ab967cf6d255390ea to your computer and use it in GitHub Desktop.
FORTRAN 90 compiling from python with numpy.f2py
def compile_fortran(source, modulename, extra_args=''):
import tempfile
import sys
import numpy.f2py
from numpy.distutils.exec_command import exec_command
try:
f = tempfile.NamedTemporaryFile(suffix='.f90')
f.write(source)
f.flush()
args = ' -c -m {} {} {}'.format(modulename, f.name, extra_args)
command = '{} -c "import numpy.f2py as f2py2e;f2py2e.main()" {}'.format(sys.executable, args)
status, output = exec_command(command)
return status, output, command
finally:
f.close()
# Example of usage
hello_source = '''
subroutine printme
print*, "Hello world!"
end
'''
status, output, command = compile_fortran(hello_source, 'hello')
import hello
hello.printme()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment