'How can I call python code from a FORTRAN Code?

I have written a python code for modeling a structure in Abaqus. I have checked it by abaqus cae noGUI=mycode.py in command window (That's how Abaqus is called to run that code). It works completely. I also have written a UMAT code in abaqus (in Fortran). I need to call the Python code in that UMAT code.

I used st=system('abaqus cae noGUI=mycode.py') and st is a integer. However, the python code is not called. I created a batch file in which I wrote abaqus cae noGUI=mycode.py. I called that file in UMAT by st=system('code.bat') and I got the error that code.bat is not recognized as an internal or external command,operable program or batch file.



Solution 1:[1]

Running an Abaqus/CAE Python script, or even calling the built-in Python interpreter, from a Fortran subroutine can certainly be done. I've found it to be very useful in certain edge-cases, with caveats. Use with caution.

You seem to be on the right track, however you must remember to use the full file path for all external files specified in an Abaqus subroutine. You'll find the Abaqus utility subroutines getjobname and getoutdir useful. Here's a barebones example snippet, with a few variable definitions tossed in:

use ifport, only: system, ierrno    !! Note: `USE` must come before any `INLCUDE`

character(len=256)                  :: outdir, jobname
character(len=:), allocatable       :: cwd, cmd
integer                             :: jobnamelen, outdirlen, rc, errnum

call getjobname(jobname, jobnamelen)
call getoutdir(outdir, outdirlen)
cwd = outdir(1:outdirlen)
cmd = 'abaqus cae nogui=' // cwd // '/my_script.py' 

rc = system(cmd)
if (rc .eq. -1) then
  errnum = ierrno( )
  print *, 'Error: ', errnum
endif

Notes:

1. If the full path is not specified, Abaqus will assume that external files exist/will be created in the scratch directory. This is not typically the same as the current work directory.

2. Code snippet shown above was tested with success using uexternaldb and a generic "hello world"-style Python script.

3. If you are using ifort 17 or later (and if you care), you should also be able to replace the ifport portability functions with the Fortran 2008 intrinsic execute_command_line.

4. You can use a batch file, however, the batch file (as well as the Python script mentioned within the batch file) must still have the full file path.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1