所以我正在使用Visual Studio代码和Python 3.7.0,而我只是想将另一个文件夹中的另一个python文件导入到我的python文件中。
这是我的文件夹结构
root/
dir1/
data.txt
task11.py
task12.py
dir2/
data.txt
task21.py
task22.py
Helpers/
FileHelper/
ReadHelper.py
例如在文件task11.py中:
from Helpers.FileHelper.ReadHelper import *
import os, sys
parentPath = os.path.abspath("../../")
if parentPath not in sys.path:
sys.path.insert(0, parentPath)
from Helpers.FileHelper.ReadHelper import *
import os, sys
sys.path.append('../../')
from Helpers.FileHelper.ReadHelper import *
上述解决方案均无效,因为我总是会遇到以下错误: ModuleNotFoundError: No module named 'Helpers'
我也尝试过:
from ..Helpers.FileHelper.ReadHelper import *
但这最终会导致错误: ValueError: attempted relative import beyond top-level package
那么如何将文件导入ReadHelper.py
到任务文件中呢?
对此也有一些类似的问题,但是它们确实很老,答案对我没有帮助。
Visual Studio代码中有一个选项,如果我使用此导入运行此命令,from Helpers.FileHelper import ReadHelper
则不会生成任何错误,并且代码可以完美执行。
缺点是此交互式窗口启动缓慢,无法处理输入。
我也尝试了@Omni的答案:
$> python -m root.dir1.task11
而且有效!但正如他所说,这有一个缺点,那就是输入终端的速度很慢。
因此,我尝试在Visual Studio Code中创建一个任务,该任务可以为我当前所在的文件执行上述shell命令,但未成功。
您知道如何在vscode中创建任务以运行上述命令吗?
我还尝试__init__.py
在每个目录下添加-files,以便将它们视为软件包Python3教程-6.4模块软件包。但这并没有帮助,并且发生了相同的错误。
我想出了一种方法,使拥有这样的文件夹结构变得非常容易,并使导入在终端中正常工作。
基本上我所做的是:
有了这个,我现在只需按即可运行带有导入的python文件cmd + shift + B
。
视觉工作室任务:
{
"version": "2.0.0",
"tasks": [
{
"label": "Run python file",
"type": "shell",
"command": "python3 /PATH_TO_ROOT_FOLDER/run_python_file.py ${file}",
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"reveal": "always",
"panel": "new",
"focus": true
}
}
]
}
我们要重点关注的部分是这一部分:
"command": "python3 /PATH_TO_ROOT_FOLDER/run_python_file.py ${file}",
python脚本:
import os, sys
# This is a argument given trough a shell command
PATH_TO_MODULE_TO_RUN = sys.argv[1]
ROOT_FOLDER = "root/"
def run_module_gotten_from_shell():
# Here I take only the part of the path that is needed
relative_path_to_file = PATH_TO_MODULE_TO_RUN.split(ROOT_FOLDER)[1]
# Creating the shell command I want to run
shell_command = createShellCommand(relative_path_to_file)
os.system(shell_command)
# Returning "python3 -m PATH.TO.MODULE"
def createShellCommand(relative_path_to_file):
part1 = "python3"
part2 = "-m"
# Here I change the string "dir1/task11.py" => "dir1.task11"
part3 = relative_path_to_file.replace("/", ".")[:-3]
shell_command = "{:s} {:s} {:s}".format(part1, part2, part3)
return shell_command
run_module_gotten_from_shell()
通过这些修改,我可以运行根目录内的任何文件,并从根目录内的任何文件导入。
而且我可以只按cmd + shift + B
。
您可以尝试使用-m
允许使用Python模块命名空间docs.python.org定位模块的选项运行脚本。
如果运行task11.py脚本,则:
$ python3 -m dir1.task11
然后在task11.py中执行如下导入:
from Helpers.FileHelper.ReadHelper import *
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句