pythonbashsubprocesscommand-line-interface

Python script to use here-document structure of Fortran binary


I use a fortran code which thakes input arguments via the "<<" here-document structure. E.g.:

program <<!
input 1
input 2
input 3
!

How can I pass the input arguments to the code from a python script? I tried several approaches using subrocess.run() but with no success, the shell seems to always wait for the final "!" and therefore, does not terminate.

I tried

here_document_input ="""<<!
input 1
input 2
input 3
!
"""
result = subprocess.run("program", input=here_document_input, text=True, shell=True)

Also, I tried to pass the input as a file

result = subprocess.run("program", "<<!", "$(cat file.input)",shell=True)

Where the file.input contains simply:

input 1
input 2
input 3
!

Solution

  • Use encode and no ! for you input (! is there to mark start and end) and don't set text.

    here_document_input ="""input 1
    input 2
    input 3
    """
    result = subprocess.run("program", input=here_document_input.encode(), shell=True)