简体   繁体   中英

How Do I Import the Redis Python Module?

I ran my project and received the following error:

File "/home/nguyentv/schoollink/web/views/apis.py", line 10, in <module>
    from util.redis.redis_client import Redis
ImportError: No module named util.redis.redis_client

How do I properly import this library?

The Module Search Path

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • the directory containing the input script (or the current directory). PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • the installation-dependent default.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

Basically, the interpreter is going to perform a lookup in your current working directory, then it will search through the system defined library directories.

The issue you are facing could be that your code is looking for a module that does not exist, you are calling the script from an incorrect directory, or the sys.path is setup incorrectly.

I could help more if you showed how you instantiated the interpreter, pwd output, and tree output.

You are trying to import Redis from a package named util . Unless this package is part of your application, it does not exist.

According to python-redis' documentation , here is how to import it:

import redis
# then use redis.Redis(...)

or, equivalently:

from redis import Redis
# then use Redis(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM