使用 sys.path.insert 时,python 找不到 fits 文件

问题描述

我想访问另一个从 fits 文件提取信息的 python 程序的输出

我通常通过以下方式做到这一点:

import sys
sys.path.insert(1,'/software/xray/Python_scripts')
from program2 import results

但是,在这种情况下,我收到以下错误

FileNotFoundError: [Errno 2] No such file or directory: 'info.fits'

当我运行 program2.py 时,它运行没有问题。所以,我不明白为什么当我从 program1.py 调用它时它无法识别 fits 文件,因此它没有给出结果!有人能指出我正确的方向吗?

谢谢。

解决方法

似乎您的导入 from program2 import results 正在搜索一个名为 info.fits 的文件,该文件很可能位于 '/software/xray/Python_scripts'

基本上,sys.path.insert 临时将路径添加到 PATH,以便操作系统从该位置执行/导入脚本。这并不意味着它也成为文件搜索路径。

您需要执行以下操作:

import os
cwd = os.getcwd()
os.chdir('/software/xray/Python_scripts')
from program2 import results
os.chdir(cwd)

这肯定是个难题,我建议您从 program2 模块中创建一个包。 https://realpython.com/python-modules-packages/