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

Linux下Python调用Fortran程序报错:source无法找到文件求助

问题解析与解决方案

一、报错核心原因

  1. 命令用途完全错误:source(或.)是用来加载Shell脚本到当前Shell环境的命令,根本不能处理Fortran源文件。你生成的是.f后缀的Fortran代码,必须先编译成可执行文件才能运行,而非直接用source执行。
  2. 语法小错误:代码里os.system("source " cmd)少了字符串拼接的+号,正确写法是os.system("source " + cmd),但就算修正这个,source依然不适合处理Fortran文件,错误本质不会改变。

二、最小修改原程序的修复方案

不需要大幅改动代码,只需把os.system的命令替换为Fortran编译+运行的指令即可(先确保Ubuntu已安装gfortran:执行sudo apt install gfortran)。

修改测试代码的最后部分:

# 替换原来的os.system("source " cmd)
# 先编译生成可执行文件,再运行
os.system("gfortran {} -o {}".format(cmd, root))
os.system("./{}".format(root))

同时修正你代码里的语法小问题(写入字符串时少了反斜杠):

# 简化文件写入逻辑,直接用w模式创建/覆盖文件
outfile = open(cmd, 'w')
outfile.write("      PROGRAM HELLOW \n")
outfile.write("      WRITE(UNIT=*, FMT=*) 'Hello World!' \n")
outfile.write("      END\n")
outfile.close()

三、改用subprocess模块的实现方式

如果必须用subprocess(比os.system更可控,能更好处理输出和错误),针对Python 2.7可以这样写:

import subprocess

# 编译Fortran代码,编译失败时会抛出异常
subprocess.check_call(["gfortran", cmd, "-o", root])

# 运行可执行程序并捕获输出
output = subprocess.check_output(["./{}".format(root)])
print("程序输出:")
print(output)

如果需要更细致的错误处理,还可以用try-except包裹,捕获编译或运行时的异常:

import subprocess

try:
    subprocess.check_call(["gfortran", cmd, "-o", root])
    output = subprocess.check_output(["./{}".format(root)])
    print(output)
except subprocess.CalledProcessError as e:
    print("执行出错:", e)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:52:23