第 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)
所有文件都在同一个目录
主要.py
import site, math
网站.py
import math
问题:改为导入标准库。
尝试 2)
site.py 和 mathtools.py(本例重命名 math.py)位于包含 main.py 的目录的子目录“include”中
主要.py
import include.site, include.mathtools
网站.py
import mathtools
问题:虽然 site.py 可以毫无问题地运行,但在运行 main.py 时语句“import mathtools”会导致未知模块。
尝试 3)
site.py 和 math.py 位于包含 main.py 的目录的子目录“include”中
主要.py
import sys, os
sys.path.append(os.path.abspath("./include"))
import include.site, include.math
网站.py
import math
问题:虽然尝试 2 中的问题已解决,但仍然存在冲突,因为数学与标准库混淆。
我理想的解决方案: 有没有一种简单的方法来声明“从与包含此导入语句的 python 文件位于同一目录中的文件导入,而不是从标准库导入”
先谢谢你了!
请您参考如下方法:
这里最简单的解决方案是不要使用自定义模块隐藏内置模块,而是使用绝对路径,但无论如何这可能会帮助您获得更多信息:
Python 将从调用它的目录中执行导入模块的函数。
例如,名为output_file 的函数位于目录tests/test1.py 中的脚本test1.py 中,它将输出一个运行时名为 test1.txt 的文本文件。如果您直接从脚本 test1.py 运行该函数,它会将文本文件输出到 /tests/test1.txt。如果您随后将 test1.py 导入到根目录中的脚本中并调用该函数,它会将文件输出到根目录。
**Directory path for visual**
├── main.py
├── (if imported and run from main, "test1.txt" is here)
├── tests
│ ├── test1.py
│ ├── (if run from test1 directly, "test1.txt" is here)
所有导入语句的执行就像从主脚本导入一样(意味着上面的尝试 3,它将导入内置的 math.py 导致 site.py 就像从根目录运行一样,并且没有 include/math.py 的绝对路径。)
