You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python脚本向采用Here-document的Fortran程序传参

问题解决方法

你的问题出在混淆了shell的Here-document语法和程序实际接收的输入内容:<<!是shell用来界定输入块的语法,不需要传递给Fortran程序,程序实际是从标准输入读取内容,直到遇到单独一行的!才停止。

以下是两种正确的实现方式:

方法一:直接传递输入内容

直接把程序需要的输入内容(包括最后一行的!)作为input参数传入,不需要加<<!:

here_document_input = """input 1
input 2
input 3
!
"""
# 推荐写法:不用shell=True,避免shell注入风险
result = subprocess.run(["./program"], input=here_document_input, text=True)

# 如果必须用shell=True,写法如下
# result = subprocess.run("program", input=here_document_input, text=True, shell=True)

方法二:通过文件传递输入

如果要借助shell的重定向功能,需要把完整的shell命令作为单个字符串传入:

# 方式1:用Here-document语法读取文件内容
result = subprocess.run("program <<!
$(cat file.input)
!
", shell=True, text=True)

# 方式2:更简单的标准输入重定向(推荐)
result = subprocess.run("program < file.input", shell=True)

其中file.input的内容保持不变:

input 1
input 2
input 3
!

关键提示

Fortran程序的逻辑是读取标准输入直到遇到单独一行的!,所以只要确保传入的标准输入包含正确的输入行和终止符即可,<<!是shell的语法,不需要出现在程序的输入内容里。

内容的提问来源于stack exchange,提问作者LC9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 20:40:01