Analysis of errors encountered when importing Python modules and when importing python modules

Source: Internet
Author: User

Analysis of errors encountered when importing Python modules and when importing python modules

When a python module cannot be imported, a module may not be installed, a module may fail to be loaded, or it may be subject to a loop import problem. This topic explains in detail.

1. The module is not installed or the path is incorrect.

ImportError: No mudule named myModule

There are two possibilities. One is that this module is not installed and can be used in general.

pip install %module_name%

. Note that sometimes the module installation package name is not the same as the name of the module to be imported. In this case, you can use the pip search | list command to find the correct package.

In another case, although the package is installed, the path of the currently running program is incorrect. Python modules will be loaded from the following locations during the python runtime:

* Current Directory

* The Value indicated by the environment variable $ PYTHONPATH is a string separated by ":". Each substring is a path of the file system.

* Standard library directory, such as the modules under dist-site-packages.

* The path specified in the. pth file, if the. pth file exists.

You can use the following method to view the path of python runtime:

import sysprint(sys.path)

Add the code in the header of the script with an error, view the printed python class library path in the console, and check whether the installation package is included in the preceding path.

* ** You can temporarily include modules not included in the path in the following way :***

sys.path.append("path/to/module")

In addition, you can view the current python path in the shell window:

echo $PYTHONPATH

2. Unable to import existing modules

If the module to be imported contains native code and native code loading (initialization) fails, this error will occur. When using ssl, gevent, and other modules involving native, if the corresponding native program is not installed, this error will occur.

Another error is that the parent module has not been imported successfully when relative paths are used for import. See the following code:

main.pymypackage/  __init__.pymymodule.pymyothermodule.py

Mymodule. py is as follows:

#!/usr/bin/env python3# Exported functiondef as_int(a):  return int(a)# Test function for module def _test():  assert as_int('1') == 1if __name__ == '__main__':  _test()

And the mythermodule code is as follows:

#!/usr/bin/env python3from .mymodule import as_int# Exported functiondef add(a, b):  return as_int(a) + as_int(b)# Test function for module def _test():  assert add('1', '1') == 2if __name__ == '__main__':  _test()

If you execute mypackage/mythermodule, the following error is reported:

Traceback (most recent call last ):
File "mythermodule. py", line 3, in <module>
From. mymodule import as_int
SystemError: Parent module ''not loaded, cannot perform relative import
[This article] (# Relative imports in Python 3) provides more detailed answers.

3. Loop Import

This error is called "circular (or cyclic) imports ". It is a unique import error in python and does not exist in languages such as java.

Assume there are two files, a. py and B. py:

#a.pyprint "a in"import sysprint "b imported: %s" % ("b" in sys.modules, )import bprint "a out"print b.x

And:

#b.pyprint "b in"import aprint "b out"x = 3

Run python a. py to obtain the following results:

$ python a.pya in          b imported: Falseb ina inb imported: Truea outTraceback (most recent call last): File "a.py", line 4, in <module>  import b File "/home/shlomme/tmp/x/b.py", line 2, in <module>  import aFile "/home/shlomme/tmp/x/a.py", line 7, in <module>  print b.xAttributeError: 'module' object has no attribute 'x'

The cause of this situation is that a circular import occurs. Loop import, and python locks during the import process. As a result, the name is referenced when Module B is not completely imported.

Determines whether the import error is caused by loop import. It mainly depends on whether there are two repeated imports in the stack. For example, a. py appears twice in the above stack, so we can judge the circular import caused by this file.

To solve this problem, you can regard the module as a resource, number all modules to be introduced, and then import them in sequence by static resource sorting method to avoid repeated import.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.