在 Python 中导入自定义函数模块

时间:2021-07-28 06:35:19

标签: python import

我在堆栈交换的 many many times 上看到过这个问题,但即使尝试了所有解决方案,我也无法让它工作。我在 python 中有一个名为 functions.py 的模块。我有另一个名为 main.py 的脚本。我正在运行 Visual Studio 代码。

当我尝试运行下面的代码时出现错误

# Import the customs functions bit
# functions.py is stored in the scripts folder of the project
sys.path.append(os.path.dirname(os.path.abspath("C:/project/scripts/")))
import functions as hlp

>>> ModuleNotFoundError: No module named 'functions'

如果我切换到 Spyder,我会尝试以下有效的代码。但是,标记的行是特定于 Spyder 的。 我希望代码能够在任何 IDE 上运行。如果您熟悉 R,那么 runfile 函数可以有效地获取文件的来源,因此 functions.py 中的所有函数都可以在环境中使用。

# Import the customs functions bit
# Source the functions file
runfile('C:/project/scripts/functions.py', wdir='C:/project/scripts/')
import functions as hlp

任何帮助都会让我开心

谢谢

0 个答案:

没有答案