第 101 次询问此类问题,但我仍然没有找到任何解决方案:
我有 3 个 python 文件:
main.py uses functions from math.py and site.py
site.py uses functions from math.py
math.py works independently
这些文件中的每一个都可以包含一个 main 函数,如果 __ name __ == __ main __ 则执行该函数,因此命令“python3 file.py”应该能够处理“file”= main/site/math的所有导入。
第二个问题是文件名 site 和 math 也是标准库的名称。
此外,程序应该是可移植的,因为导入不应包含其他 python 文件的绝对路径。
需要什么导入语句?
试试 1)
所有文件都在同一个目录中
主文件
import site, math
网站.py
import math
问题:改为导入标准库。
试试 2)
site.py 和 mathtools.py(在本例中重命名 math.py)位于包含 main.py 的目录的子目录“include”中
主文件
import include.site, include.mathtools
网站.py
import mathtools
问题:虽然 site.py 可以毫无问题地运行,但运行 main.py 时,“import mathtools”语句会导致未知模块。
试试 3)
site.py 和 math.py 位于包含 main.py 的目录的子目录“include”中
主文件
import sys, os
sys.path.append(os.path.abspath("./include"))
import include.site, include.math
网站.py
import math
问题:虽然尝试 2 中的问题已解决,但仍然存在冲突,因为数学与标准库混淆了。
我理想的解决方案:有没有一种简单的方法来说明“从与包含此导入语句的 python 文件位于同一目录中的文件导入,而不是从标准库导入”
提前谢谢你!