I’m currently working on a project and I keep getting this error when executing a Python script:
File "D:projectscompanyspiderscountryspaincitiesrunnablesshort.py", line 22, in <module>
soup = get_soup_from_url(url, "html.parser")
NameError: name 'get_soup_from_url' is not defined
The function "get_soup_from_url" is getting imported from another file that’s located on another directory. In order of giving a minimal reproducible example i made this little project where I’m getting the same error with just two basic scripts. Here are the two scripts:
short.py
import sys
sys.path.append('../../../../utils')
from driver import *
print_on_console('Hello world!')
driver.py
def print_on_console(message):
print(message)
So basically I get this error when trying to import the function "print_on_console" into short.py. The project structure follows this:
- spiders
- country
- portugal
- cities
- runnable
- short.py
- utils
- driver.py
I’m sharing this project with other people and they don’t have this error with the exact same code, so I guess I missed something when configuring my visual studio code for python but I’ve been two days searching for what’s wrong without finding any solution.
Thanks to anyone who gives me any information in advance.
2
Answers
Method
get_soup_from_url
is from another "utils" existing python library.The simplest way is to check your utils into something else and unique.
If that fixes your problem, try using relative imports to ensure you are importing correct "utils".
sys.path.append('../../../../utils')
this does not point to the desired folder.sys.path
is a list of folders/directories where the Python interpreter searches for modules. So it is not aware of where your working directory is or where does this Python file runs. It is just a regular list that you can append anything to it.So, what your command does is it adds
'../../../../utils'
to the end ofsys.path
.You can check this by running
print(sys.path)
after this line. You will see something like this at the end:instead you should point the full path to it as an argument
try this:
output: