目前,我非常困惑python中的导入是如何工作的。基本上,我不明白为什么以模块的形式启动脚本(使用-m)会改变行为:我在一个名为two的文件夹中有两个脚本。一个叫Programm.py,另一个叫Test_Programm.py。
Test_Programm.py中的第一行是:from Testing.Programm import my_function
使用命令行Test_Programm.py从测试的父文件夹运行python -m Testing。Test_Programm按预期工作,它按预期导入所有内容。在带有python -m Test_Programm的测试文件夹中运行它不会得到导入。在父文件夹中运行它,因为python Testing\Test_Programm.py不工作。当使用python Test_Programm.py在测试文件夹中运行时,它也不起作用。
为什么是这样,python是如何寻找模块的呢?
所有测试都是使用Python3.8.0完成的
堆栈跟踪:
父文件夹中的python Testing\Test_Programm.py:
Traceback (most recent call last):
File "Testing\Test_Programm.py", line 8, in <module>
from Testing.Test_Programm import my_function
ModuleNotFoundError: No module named 'Testing'测试文件夹中的python Test_Programm.py:
Traceback (most recent call last):
File "Test_Programm.py", line 8, in <module>
from Test_Programm import my_function
ModuleNotFoundError: No module named 'Testing'测试文件夹中的python -m Test_Programm.py:
Traceback (most recent call last):
File "C:\Python38\lib\runpy.py", line 192, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Python38\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\<username>\PycharmProjects\TestingTesting\src\Testing\Test_Programm.py", line 8, in <module>
from Testing.Test_Programm import my_function
ModuleNotFoundError: No module named 'Testing'发布于 2021-02-11 01:39:15
每文档
在程序启动时初始化时,此列表的第一项
path[0]是包含用于调用Python解释器的脚本的目录。如果脚本目录不可用(例如,如果以交互方式调用解释器或从标准输入读取脚本),则path[0]是空字符串,它指示Python首先搜索当前目录中的模块。
和每一个Python命令行文档
当使用
-m module-name调用时,给定模块位于Python路径上,并作为脚本执行。
第二个引用的一个含义是,-m调用方法并不是sys.path描述的“运行脚本”,因为它必须首先设置sys.path,然后查找要执行的模块,所以它不能使path[0]与脚本目录匹配(在解释器进行初始设置之后,sys.path通常不会以编程方式修改,然后是site模块)。
在他们俩之间,这个回答了你的问题。由于您的目录不是“始终在”sys.path的一部分,所以您依赖于sys.path中的第一个条目的隐式行为。
这些案件是:
python3 Testing/Test_Programm.py:sys.path[0]是Testing/,所以当您从Testing.Programm导入时,它在sys.path中找不到带有Testing子目录的任何条目并放弃(python3 Test_Programm.py也是如此;脚本文件夹中没有Testing )python3 -mTest_Programm也不起作用;sys.path[0]首先搜索当前目录,然后再一次没有Testing子目录python3 -mTesting.Test_Programm之所以工作,是因为它正在查找要运行的模块,而不是直接执行脚本,因此path[0]仍然是工作目录,其中有一个Testing子目录。它找到它,在它里面找到Test_Programm.py,当它运行时,它仍然根搜索在Testing下面,所以从Testing.Programm工作导入。https://stackoverflow.com/questions/66147496
复制相似问题