【发布时间】:2021-12-11 16:30:58
【问题描述】:
我想从 Python 运行已编译的 Fortran 数值模型。使用 F2PY 编译它而不在 Fortran 例程中实现一些更改太复杂了。这就是为什么我只是使用 subprocess 模块调用它的可执行文件。
问题是我必须调用它几千次,而且我觉得生成这么多 shell 会减慢整个过程。
我的实现(很难提供可重现的示例,抱歉)看起来像:
import os
import subprocess
foo_path = '/path/to/compiled/program/'
program_dir = os.path.join(foo_path, "FOO") #FOO is the Fortran executable
instruction = program_dir + " < nlst" #It is necesary to provide FOO a text file (nlst)
#with the configuration to the program
subprocess.call(instruction, shell=True, cwd=foo_path) #run the executable
以这种方式运行它(在循环内),它运行良好,FOO 生成一个文本文件输出,我可以从 python 中读取它。但我想做同样的事情,保持 shell 处于活动状态,并只向它提供"nlst" 文件路径。另一个不错的选择可能是启动一个空 shell 并让它等待instruction 字符串,它看起来像"./FSM < nlst"。但是我不确定该怎么做,有什么想法吗?
谢谢!
[已编辑] 这样的事情应该可以工作,但 .comunicate 结束 process 并且第二次调用不起作用:
from subprocess import Popen, PIPE
foo_path = '/path/to/FOO/'
process = Popen(['bash'], stdin=PIPE, cwd=foo_path)
process.communicate(b'./FOO < nlst')
【问题讨论】:
-
您可以使用管道(请参阅 popen())来允许您的 python 脚本发送字符串。在管道的另一端,您运行一个执行
read的 shell 脚本,并使用它刚刚从标准输入读取的参数启动您的 Python 脚本。 -
也许线程对你有用 - link
-
谢谢@Ronald。我认为你的方法正是我想要的。但不确定如何实现它。我将尝试编辑问题
标签: python subprocess popen