Méthode utilisant le module Subprocess
Script Python:
import numpy as np
import math
import subprocess
def function(x):
y1 = x**4 + 2*x**3 + 4*x**2 + 1
y2 = x**2
return y1,y2
x = 1.0
print function(x)
#---------- Now using Fortran Code ----------#
i=0
command = ['CodeFortran', str(x)]
process = subprocess.Popen(command, stdout=subprocess.PIPE)
while True:
text = process.stdout.readline()
if text != '':
y1, y2 = text.split()
print float(y1), float(y2)
i=i+1
else:
break
print 'Number of line:', i
Code Fortran:
program BasicFortranCode
implicit none
integer none
integer, parameter :: pr = selected_real_kind(15,3)
real(pr) :: x
character :: arg
call getarg(1,arg)
read(arg,*) x ! Convert String to Real
write(6,*) x**4 + 2*x**3 + 4*x**2 + 1, x**2
end program
Méthode utilisant le module f2py
f2py -c -m FortranModule CodeFortran02.f90
FortranModule.so
python ExamplePythonScriptUsingFortran02.py
Script Python:
import numpy as np
import math
import subprocess
import FortranModule
def function(x):
y1 = x**4 + 2*x**3 + 4*x**2 + 1
y2 = x**2
return y1,y2
x = 1.0
print 'From python: ', function(x)[0], function(x)[1]
#---------- Now using Fortran Code ----------#
FortranModule.test.x = 1.0
FortranModule.test.foo()
Code Fortran:
module test
integer, parameter :: pr = selected_real_kind(15,3)
real(pr) :: x
contains
subroutine foo
implicit none
write(6,*) 'From Fortran', x**4 + 2*x**3 + 4*x**2 + 1, x**2
end subroutine foo
end module test
Références
Liens |
------------- | -------------
f2py page |
subprocess page |
python: reading subprocess output in threads |
read subprocess stdout line by line |
How to get output from subprocess.Popen() |
fortran f2py page |