I'm using Visual Studio Code and Python 3.7.0 and I'm just trying to import another Python file, from another folder, into my python file.
Here is my folder structure
root/
dir1/
data.txt
task11.py
task12.py
dir2/
data.txt
task21.py
task22.py
Helpers/
FileHelper/
ReadHelper.py
e.g. in the file 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 *
None of the above solutions works as I always end up with the error:
ModuleNotFoundError: No module named 'Helpers'
I've also tried:
from ..Helpers.FileHelper.ReadHelper import *
But it ends up with the error: ValueError: attempted relative import beyond top-level package
So how can I import the file ReadHelper.py
to my task files?
There are some similar questions to this but they are really old and the answers have not helped me.
There is an option in Visual Studio code, If I run this command with this import
from Helpers.FileHelper import ReadHelper
then no errors are generated and the code executes perfectly.
One downside is that this interactive window is slow at starting and it cannot handle inputs.
I tried the answer of @Omni as well:
$> python -m root.dir1.task11
And it worked! but as he said, there is a downside: it is slow to type in the terminal.
So I tried to create a task in Visual Studio Code that could execute the above shell command for the file that I'm currently in, but did not succeed.
Do you know how to create a task in vscode to run the above command?
I've also tried to add __init__.py
-files under every directory so they would be seen as packages Python3 tutorial - 6.4 Module Packages. But this didn't help and the same error occurred.
I come up with a way to make it really easy to have a folder structure like this and get the imports to work correctly in the terminal.
Basically what I did was:
With this, I can now run my python files, with the imports, by only pressing cmd + shift + B
.
The visual studio task:
{
"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
}
}
]
}
The part that we want to focus on is this one:
"command": "python3 /PATH_TO_ROOT_FOLDER/run_python_file.py ${file}",
The python script:
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()
With these modifications, I can run any file inside the root directory with imports from any file inside the root directory.
And I can do it by only pressing cmd + shift + B
.
You could try running the script with the -m
option that allows modules to be located using the Python module namespace docs.python.org.
If you run the task11.py script then:
$ python3 -m dir1.task11
And in the task11.py do the import like:
from Helpers.FileHelper.ReadHelper import *
If you're only trying to do this in VSCode, and not during normal run time. You can add the path in the .vscode/settings.json
{
"python.analysis.extraPaths": [
"${workspaceFolder}/webapp"
],
}
NOTE: This does not solve standard Python importing. My use-case was specific to a monolithic project where all editor config files where in the root and thus I couldn't open 'webapp/' as a workspace itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With