下图是目录结构
t11.py内容:
from ..t2 import t21
t = t21.hello()
t21.py内容:
def hello():
print("Hello!")
法一:
如果你的文件夹名不带中划线 ,将t11.py内容改成如下所示:
import sys
sys.path.insert(0, sys.path[0]+"/../")
from test-t.t2 import t21 #注意这里是错的,test-t中不能有中划线。也就是说你的文件夹名中不能有中划线。
t = t21.hello()
法二:
在vscode中,打开test-t文件夹,打开t11.py,直接按F5运行会报错: 发生异常: ImportError (note: full exception trace is shown but execution is paused at: _run_module_as_main)
attempted relative import with no known parent package
解决方法是先进到上一级目录,再使用模块方式运行:
如果想调试,需要修改launch.json文件。把program改成module内容如下,并添加"cwd"内容如下
如果你vscode打开的是test-t的父目录,则后面不需要加/..
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python 调试程序: 当前文件",
"type": "debugpy",
"request": "launch",
// "program": "${file}",
"module": "test-t.t1.t11",
"cwd": "${workspaceFolder}/..",
"console": "integratedTerminal"
}
]
}
打开t11.py,按F5也能成功了。
这个方法缺点是不论点哪个文件运行的都是test-t.t1.t11
另外不建议文件夹带中划线 - 因为python变量不支持中划线,我用test-t是为了测试一下能否用,因为有时候从网上下的代码文件夹名容易有中划线。如果不带中划线,t11.py中还可用这样导入:
from test-t.t2 import t21
t = t21.hello()
还有,在代码中打开文件的相对路径应该是test-t/开头。
法三:
也可以在开头加入这样的代码,后面的注释是防止autopep8自动移动顺序:
import sys
sys.path.insert(0, sys.path[0]+"/../") # NOQA: E402