【问题标题】:Fortran not receiving input from subprocess.runFortran 未从 subprocess.run 接收输入
【发布时间】:2021-07-01 22:35:31
【问题描述】:

我正在尝试使用 subprocess 模块从 python 运行 fortran90 代码。有问题的 fortran 代码提示用户输入,但我希望子进程通过可选参数 input 提供该输入。 但是,当我这样做时,fortran 运行,提示输入,什么也没收到,并且似乎坐在 read 语句上。调用等效的 python 脚本时,相同的代码可以工作。

我还使用 capture_output 将输出写入文件。我已验证问题仍然存在,即使已删除。

我已经包含了我想做的简单版本,包括 python 和 fortran 版本。 这是调用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)

fortran

program readwrite

  implicit none
  character(len=99) :: readwrite 

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

和蟒蛇

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

如果有帮助,控制台输出

(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

我在 python 版本 3.8.3 上并使用 ifort/2017.1.132-GCC-5.4.0-2.26 编译器 非常感谢

【问题讨论】:

    标签: python io fortran subprocess


    【解决方案1】:

    所以我自己偶然发现了答案。 Fortran 将继续读取,直到遇到行尾字符。因此,修复我上面的示例所需要做的就是将换行符放入输入字符串中,如下所示

    send = b'input\n'
    

    【讨论】:

    • 你写道:“所以我自己偶然发现了答案。”,请给 / 参考。
    • 对不起,我所说的“偶然发现”实际上是指我设法解决了问题,而不是我在某处找到了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 2014-07-12
    • 2021-08-24
    相关资源
    最近更新 更多