简体   繁体   中英

Fortran not receiving input from subprocess.run

I am attempting to run fortran90 code from python using the subprocess module. The fortran code in question prompts the user for input, but I want subprocess to provide that input through the optional argument input . When I do this however, the fortran runs, prompts for input, receives nothing and appears to sit at the read statement. The identical code works when calling an equivalent python scripts.

I am also writing the output to a file using capture_output. I have verified that the problem remains, even with that removed.

I have included simple versions of what I want to do, both the python and fortran versions. Here is the code that calls the python/fortran

import os
import subprocess

output1 = os.getcwd() = '/output1'
output2 = os.getcwd() = '/output1'

send = b'input' #b as require bytes type data input

#Call to python code
result = subprocess.run(['python','test.py'],input=send,capture_output=True)

with open(output1,'w') as f:
    f.write(result.stdout)

#Call to fortran code
result = subprocess.run(['./test'],input=send,capture_output=True)

with open(output2,'w') as f:
    f.write(result.stdout)

the fortran

program readwrite

  implicit none
  character(len=99) :: readwrite 

  write(*,*) "enter something"
  read(*,*) readwrite
  write(*,*) readwrite

and the python

readwrite = input('enter something')
print(readwrite)

The console output if it helps

(base) [a1724542@l01 testing]$ python caller.py
^CTraceback (most recent call last):
  File "caller.py", line 18, in <module>
    result = subprocess.run(['./test'],input=send,capture_output=True)
  File "/apps/skl/software/Anaconda3/2020.07/lib/python3.8/subprocess.py", line 491, in run
    stdout, stderr = process.communicate(input, timeout=timeout)
  File "/apps/skl/software/Anaconda3/2020.07/lib/python3.8/subprocess.py", line 1024, in communicate
    stdout, stderr = self._communicate(input, endtime, timeout)
  File "/apps/skl/software/Anaconda3/2020.07/lib/python3.8/subprocess.py", line 1866, in _communicate
    ready = selector.select(timeout)
  File "/apps/skl/software/Anaconda3/2020.07/lib/python3.8/selectors.py", line 415, in select
    fd_event_list = self._selector.poll(timeout)
KeyboardInterrupt

(base) [a1724542@l01 testing]$ cat output1
promptinput
(base) [a1724542@l01 testing]$ cat output2
cat: output2: No such file or directory

I am on python version 3.8.3 and using the ifort/2017.1.132-GCC-5.4.0-2.26 compiler Many thanks

So I stumbled across the answer myself. Fortran will keep reading until it encounters an end of line character. So all that is required to fix my example above is to put a newline character into the input string like so

send = b'input\n'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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