그래서 저는 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에서 현재있는 파일에 대해 위의 셸 명령을 실행할 수있는 작업을 만들려고했지만 성공하지 못했습니다.
위의 명령을 실행하기 위해 vscode에서 작업을 생성하는 방법을 알고 있습니까?
나는 또한 __init__.py
모든 디렉토리 아래 에 -files 를 추가하려고 시도하여 Python3 tutorial-6.4 Module Packages 패키지로 표시 됩니다. 그러나 이것은 도움이되지 않았고 동일한 오류가 발생했습니다.
나는 이와 같은 폴더 구조를 갖는 것을 정말 쉽게 만들고 터미널에서 가져 오기가 올바르게 작동하도록하는 방법을 생각해 냈습니다.
기본적으로 내가 한 일은 다음과 같습니다.
이것으로 나는 이제 단지를 눌러서 가져 오기와 함께 파이썬 파일을 실행할 수 있습니다 cmd + shift + B
.
Visual Studio 작업 :
{
"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}",
파이썬 스크립트 :
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] 삭제
몇 마디 만하겠습니다