Home > Blockchain >  NameError: name 'X' is not defined but it is
NameError: name 'X' is not defined but it is

Time:09-16

I'm currently working on a project and I keep getting this error when executing a Python script:

File "D:\projects\company\spiders\country\spain\contrataciondelestado\runnables\short.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
      - spain
         - contrataciondelestado
            - 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.

CodePudding user response:

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".

CodePudding user response:

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 of sys.path.

You can check this by running print(sys.path) after this line. You will see something like this at the end:

, '../../../../utils']

instead you should point the full path to it as an argument

try this:

import sys
from pathlib import Path

p = str(Path(__file__).parents[4]) #4 folders up

sys.path.append(p   '\\utils')

from driver import *

print_on_console('Hello world!')

output:

(base) PS C:\Users\dasani\Sandbox\trash\test_delete> & C:/Users/dasani/Anaconda3/python.exe c:/Users/dasani/Sandbox/trash/test_delete/country/spain/contrataciondelestado/runnable/short.py
Hello world!

CodePudding user response:

Have you checked Python and library version?

pip freeze requirements.txt

This command can works to check it you have the same like them

  • Related